public function inscription(\Slim\Slim $app)
 {
     $allPostVars = $app->request->post();
     $username = $allPostVars['username'];
     $mail = $allPostVars['mail'];
     $mdp = $allPostVars['mdp'];
     try {
         $db = getDB();
         $verif = $db->prepare("SELECT username \n\t\t\t\tFROM users\n\t\t\t\tWHERE username = :username");
         $verif->bindParam(':username', $username, PDO::PARAM_INT);
         $verif->execute();
         $usernamed = $verif->fetch(PDO::FETCH_OBJ);
         $verif->closeCursor();
         if ($usernamed) {
             $answer = "Ce nom d'utilisateur est déjà pris, merci de retenter avec un nouveau.";
         } else {
             $sth = $db->prepare("INSERT INTO users \n\t\t\t\t(username, mail, mdp)\n\t\t\t\tVALUES (:username, :mail, :mdp)");
             $sth->bindParam(':username', $username, PDO::PARAM_INT);
             $sth->bindParam(':mail', $mail, PDO::PARAM_INT);
             $sth->bindParam(':mdp', $mdp, PDO::PARAM_INT);
             $sth->execute();
             $answer = array("status" => "success", "code" => 1);
         }
         $app->response->setStatus(200);
         $app->response()->headers->set('Content-Type', 'application/json');
         echo json_encode($answer);
         $db = null;
     } catch (PDOException $e) {
         $app->response()->setStatus(404);
         echo '{"error":{"text":' . $e->getMessage() . '}}';
     }
 }
Exemple #2
1
 public function Delete($files, \Slim\Slim &$app, $page)
 {
     $obj = new Files();
     $obj->parseFile($files);
     $user_id = $obj->user_id;
     //$cookieDB = $obj->cookie;
     $cookie = $app->getCookie('username');
     $db = $app->db;
     $logged = new Logged();
     $id = $logged->getLogged($db, $cookie);
     //checking of the user is registered in Users table as the user or anonymous which added this file and getting his id
     if ($id == $user_id) {
         $foo = new Foo();
         $foo->token = $page;
         $mapper = new FooMapper($db);
         $files = $mapper->delete($foo);
         $path = $obj->path;
         $filename = "uploads/" . $path;
         //deleting file from the folder
         unlink($filename);
         $app->redirect('/TwigBlog/');
     } else {
         $app->error();
     }
 }
Exemple #3
1
 /**
  * Load config into slim configuration
  * @param Slim $app
  */
 public function refresh(Slim $app = null)
 {
     if ($app != null) {
         $this->app = $app;
     }
     $this->app->config($this->config);
 }
Exemple #4
1
 /**
  * Setup the form service.
  *
  * @param \Slim\Slim $app The application instance.
  */
 public static function setup(Slim $app)
 {
     $app->container->singleton('form', function () use($app) {
         $prefix = $app->config('form.prefix');
         return new Form($prefix ?: null);
     });
 }
Exemple #5
1
function loginUser(\Slim\Slim $slimApp)
{
    //echo "middleware:loginUser";
    $request = $slimApp->request;
    $response = $slimApp->response();
    $response->headers->set('Content-Type', 'application/json');
    //
    $userData = json_decode($request->getBody());
    $name = $userData->userName;
    $password = $userData->password;
    $email = $userData->email;
    //
    $dbUtil = new \icraft\DBUtil();
    $DBH = $dbUtil->getConnection();
    // $sql = "SELECT * FROM `users` WHERE uName=\'saumya\' && uPassword=\'saumyaPW1\'";
    //$STH = $DBH->prepare("SELECT * FROM `users` WHERE uName='$name' && uPassword='******'");
    $STH = $DBH->query("SELECT * FROM `users` WHERE uName='{$name}' && uPassword='******'");
    $STH->setFetchMode(PDO::FETCH_ASSOC);
    //$STH->execute();
    //var_dump($STH);
    $response->body('FAIL');
    // Default FAIL
    while ($row = $STH->fetch()) {
        /*
        echo $row['uName'] . "\n";
        echo $row['uPassword'] . "\n";
        echo $row['uEmail'] . "\n";
        */
        $n = $row['uName'];
        $p = $row['uPassword'];
        $e = $row['uEmail'];
        $responseObj = "{'status':'SUCCESS','userObj':{'name':{$n},'password':{$p},'email':{$e}}}";
        $response->body($responseObj);
    }
}
Exemple #6
1
 /**
  * This methods will be called at application startup
  * @param $appInstance
  * @return void
  */
 public static function addRouteDefinitions(Slim $appInstance)
 {
     $appInstance->post('/ajax', function () use(&$appInstance) {
         $exceptionContentType = 'text/plain';
         $appInstance->response->headers->set('Cache-Control', 'no-store');
         try {
             $contentType = EmaRpcApi::slimCallback($appInstance);
             $appInstance->response->headers->set('Content-Type', $contentType);
         } catch (SecurityException $e) {
             $appInstance->response->setStatus(401);
             $appInstance->response->headers->set('Content-Type', $exceptionContentType);
             print "Unauthorized.\n" . $e->getMessage();
         } catch (\RuntimeException $e) {
             $appInstance->response->setStatus(400);
             $appInstance->response->headers->set('Content-Type', $exceptionContentType);
             print $e->getMessage();
             $logger = new DbLogger();
             $logger->writeException($e);
         } catch (\Exception $e) {
             $logger = new DbLogger();
             $logger->writeException($e);
             $appInstance->response->setStatus(500);
             $appInstance->response->headers->set('Content-Type', $exceptionContentType);
             $msg = "Server Error Occurred. Please contact us. Error code is: " . $e->getCode();
             if (EMA_DEBUG === true) {
                 $msg = $e->getMessage() . ";\n Code: " . $e->getCode() . "\n\n\n" . $e->getTraceAsString();
             }
             print $msg;
         }
     });
     if (EMA_REST_API) {
         $appInstance->map('/rest/:path+', function ($path) use($appInstance) {
             $appInstance->response->headers->set('Cache-Control', 'no-store');
             $appInstance->response->headers->set('Content-Type', 'application/json');
             $printoutError = function (\Exception $e, $status = 500) use($appInstance) {
                 $appInstance->response->setStatus($status);
                 print EmaRestApi::getErrorOutput($e);
             };
             try {
                 $rpc = EmaRestApi::rpcFactory($path, $appInstance->request->getMethod(), $appInstance);
                 $result = EmaRestApi::rpcCheckAndRun($rpc, $appInstance);
                 if (EmaRestApi::$isAddition) {
                     $appInstance->response->setStatus(201);
                     $appInstance->response->headers->set('Location', EmaRestApi::$additionRouteBase);
                 }
                 print json_encode($result);
             } catch (InputError $e) {
                 $printoutError($e, 400);
             } catch (SecurityException $e) {
                 $printoutError($e, 403);
             } catch (NotFound $e) {
                 $printoutError($e, 404);
             } catch (Unsupported $e) {
                 $printoutError($e, 415);
             } catch (\Exception $e) {
                 $printoutError($e, 500);
             }
         })->via('GET', 'POST', 'DELETE');
     }
 }
Exemple #7
1
 protected function appendRoute($routes, $prefix = '')
 {
     $bootstrap = $this;
     foreach ($routes as $item) {
         if (is_object($item)) {
             /* @var $item MvcContext */
             $context = $item;
             $context->app = $this;
             $context->rewriteBase = $this->rewriteBase;
             if (!is_array($item->path)) {
                 $item->path = array($item->path);
             }
             foreach ($item->path as $path) {
                 $map = $this->slim->map($prefix . $path, function () use($bootstrap, $context) {
                     $bootstrap->executeAction($context, func_get_args());
                 });
                 //via method
                 $methods = array();
                 if ($context->method == '*') {
                     $methods = array('GET', 'POST', 'PUT', 'DELETE', 'OPTIONS', 'PATCH');
                 } else {
                     $methods = explode(',', strtoupper($context->method));
                 }
                 call_user_func_array(array($map, 'via'), $methods);
             }
         } else {
             if (!is_array($item->path)) {
                 $item->path = array($item->path);
             }
             foreach ($item->path as $path) {
                 $this->appendRoute($item, $prefix . $path);
             }
         }
     }
 }
 /**
  * Open a database connection
  *
  * @param \Slim\Slim $app
  * @return \PDO
  */
 public static function openDatabase($app)
 {
     $dsn = $app->config('database.dsn');
     $user = $app->config('database.user');
     $pass = $app->config('database.pass');
     return new \PDO($dsn, $user, $pass);
 }
 private function request($method, $path, $data = array(), $optionalHeaders = array())
 {
     // Capture STDOUT
     ob_start();
     $options = array('REQUEST_METHOD' => strtoupper($method), 'PATH_INFO' => $path, 'SERVER_NAME' => 'local.dev');
     if ($method === 'get') {
         $options['QUERY_STRING'] = http_build_query($data);
     } elseif (is_array($data)) {
         $options['slim.input'] = http_build_query($data);
     } else {
         $options['slim.input'] = $data;
     }
     // Prepare a mock environment
     Slim\Environment::mock(array_merge($options, $optionalHeaders));
     $env = Slim\Environment::getInstance();
     $this->app->router = new NoCacheRouter($this->app->router);
     $this->app->request = new Slim\Http\Request($env);
     // Custom headers
     $this->app->request->headers = new Slim\Http\Headers($env);
     $this->app->response = new Slim\Http\Response();
     // Establish some useful references to the slim app properties
     $this->request = $this->app->request();
     $this->response = $this->app->response();
     // Execute our app
     $this->app->run();
     // Return the application output. Also available in `response->body()`
     return ob_get_clean();
 }
Exemple #10
0
 public static function configureModes(Slim $app, array $modeConfigs)
 {
     foreach ($modeConfigs as $mode => $config) {
         $app->configureMode($mode, function () use($app, $config) {
             $app->config($config);
         });
     }
 }
Exemple #11
0
 public function get($msg = null)
 {
     $data = [];
     if (!is_null($msg)) {
         $data['message'] = $msg;
     }
     $this->slim->render('login.twig', $data);
 }
 protected function render($template, $data = array(), $status = null)
 {
     try {
         $this->application->render($template, $data, $status);
     } catch (Twig_Error_Runtime $e) {
         $this->application->render('Error/app_load_error.html.twig', array('message' => sprintf('An exception has been thrown during the rendering of a template ("%s").', $e->getMessage()), -1, null, $e));
     }
 }
 /**
  * Configure the middleware layers for your application
  *
  * @param Slim $app
  */
 public function configure(Slim $app)
 {
     $this->init($app->container);
     /** @var MiddlewareProvider $middleware */
     foreach ($this->middleware as $middleware) {
         $app->add($middleware);
     }
 }
Exemple #14
0
 public function get()
 {
     $cookieName = session_name();
     $sessionParams = session_get_cookie_params();
     // Unset cookie in browser
     setcookie($cookieName, false, 1, $sessionParams['path'], $sessionParams['domain'], $sessionParams['secure']);
     $this->slim->redirect($this->slim->request->getRootUri() . '/login');
 }
Exemple #15
0
 public function setUp()
 {
     parent::setUp();
     $app = new Slim();
     $app->get('/test', function () {
     })->name('test');
     $this->ext = new Xhgui_Twig_Extension($app);
 }
 /**
  * @param Slim $slim
  *
  * @return null
  */
 public function configure(Slim $slim)
 {
     foreach ($this->hooks as $event => $hooks) {
         foreach ($hooks as $hook) {
             $slim->hook($event, $this->hookClosure($slim, $hook));
         }
     }
 }
Exemple #17
0
 /**
  * constructor
  */
 final function __construct()
 {
     self::$app || (self::$app = \Slim\Slim::getInstance());
     $this->request = self::$app->request();
     $this->response = self::$app->response();
     $this->config = self::$app->config;
     $this->validator = self::$app->validator;
     $this->init();
 }
Exemple #18
0
 public function __construct(StorageInterface $storage, Slim $app)
 {
     $this->storage = $storage;
     $this->app = $app;
     $this->ignored = $app->config('api.classes.auth.ignored');
     if (!is_array($this->ignored)) {
         $this->ignored = array();
     }
 }
Exemple #19
0
 /**
  * Adds services to the Statical Manager
  *
  * @param \Statical\Manager $manager
  * @param \Slim\Slim $slim
  */
 protected static function addServices($manager, $slim)
 {
     $services = array('Input' => 'request', 'Request' => 'request', 'Response' => 'response', 'View' => 'template');
     $container = $slim->getContainer();
     foreach ($services as $alias => $id) {
         $proxy = __NAMESPACE__ . '\\' . $alias;
         $manager->addProxyService($alias, $proxy, $container, $id);
     }
 }
Exemple #20
0
 public function __construct(Slim $slim)
 {
     $this->slim = $slim;
     if ($log = $slim->getLog()) {
         $this->originalLogWriter = $log->getWriter();
         $log->setWriter($this);
         $log->setEnabled(true);
     }
 }
Exemple #21
0
 protected function getFramework($config)
 {
     $app = new Slim(['view' => new Twig()]);
     $app->config(['templates.path' => $config['templates.path']]);
     $view = $app->view();
     $view->parserOptions = $config['parserOptions'];
     $view->parserExtensions = array(new TwigExtension());
     return $app;
 }
Exemple #22
0
 public static function registrationRoute(\Slim\Slim $app)
 {
     $app->get('/', function () use($app) {
         $app->render('index.php');
     });
     $app->post('/form/', function () use($app) {
         $app->render('index.php', ['nickname' => $_POST['nickname']]);
     });
 }
Exemple #23
0
 /**
  * Constructor
  * 
  * @param \Slim\Slim $app Slim app reference
  */
 public function __construct(\Slim\Slim $app)
 {
     $this->app = $app;
     $this->app->notFound(function () use($app) {
         $data = array('error' => array('message' => 'Invalid route'));
         $app->contentType('application/json');
         $app->halt(400, json_encode($data));
     });
 }
Exemple #24
0
 public function post()
 {
     // Read JSON from Body-input
     $requestData = json_decode($this->slim->request->getBody());
     // Create feed
     $feedId = $this->feedsDao->create($_SESSION['user']['id'], ['name' => $requestData->name, 'website_uri' => $requestData->website_uri, 'feed_uri' => $requestData->feed_uri, 'update_interval' => $requestData->update_interval]);
     // Redirect to the new API-Resource to tell the client where it is
     $this->slim->redirect($this->slim->request->getRootUri() . '/api/feeds/' . $feedId);
 }
Exemple #25
0
 /**
  * Setup the pagination service.
  *
  * @param \Slim\Slim $app The application instance.
  */
 public static function setup(Slim $app)
 {
     $key = $app->config('pagination.key');
     if (empty($key)) {
         $key = 'page';
     }
     Paginator::currentPageResolver(function () use($app, $key) {
         return $app->request->get($key);
     });
 }
 public function getSlimInstance()
 {
     $slim = new Slim(array('version' => '0.0.0', 'debug' => false, 'mode' => 'testing'));
     // force to overwrite the App singleton, so that \Slim\Slim::getInstance()
     // returns the correct instance.
     $slim->setName('default');
     // make sure we don't use a caching router
     $slim->router = new NoCacheRouter($slim->router);
     return $slim;
 }
 public function generateRoutes()
 {
     foreach ($this->schema->table as $table) {
         $tableName = $this->_urlFriendly($table['name']);
         $this->slimApp->post($this->apiBasePath . "add-" . $tableName, $this->_addRecord($table));
         $this->slimApp->get($this->apiBasePath . "fetch-" . $tableName . "s", $this->_fetchRecords($table));
         $this->slimApp->get($this->apiBasePath . "get-" . $tableName . "/:id", $this->_getRecord($table));
         $this->slimApp->get($this->apiBasePath . "get-" . $tableName . "-by/:key/:value", $this->_getRecordBy($table));
     }
 }
Exemple #28
0
 public function action_update(Slim $app, $setupId, $fitId)
 {
     if (!$app->user->isLoggedin()) {
         return false;
     }
     $newFit = $app->request()->post('fit');
     $newDesc = $app->request()->post('description');
     $newQuantity = $app->request()->post('quantity');
     $app->evefit->updateFit($newFit, $newDesc, $newQuantity, $setupId, $fitId);
 }
Exemple #29
0
 /**
  * Returns partialHTML of a list of fits.
  *
  * @param \Slim\Slim $app
  */
 public function action_fitList(Slim $app, $setupId, $fitId)
 {
     if (!$app->user->isLoggedin()) {
         return false;
     }
     $setup = $app->evefit->getSetup($setupId);
     $fit = $setup->getFit($fitId);
     $tour = $app->rulechecker->getTournament();
     $app->render('fit/fit.twig', array('setup' => $setup, 'fit' => $fit, 'tournament' => $tour));
 }
 public function request($method, $path, $options = array())
 {
     ob_start();
     Environment::mock(array_merge(array('PATH_INFO' => $path, 'SERVER_NAME' => 'slim-test.dev', 'REQUEST_METHOD' => $method), $options));
     $app = new Slim();
     $this->app = $app;
     $this->request = $app->request();
     $this->response = $app->response();
     return ob_get_clean();
 }