Example #1
0
 /**
  * @dataProvider authenticationDataProvider
  */
 public function testRouteAuthentication($requestMethod, $path, $location, $hasIdentity, $identity, $httpStatus)
 {
     \Slim\Environment::mock(array('REQUEST_METHOD' => $requestMethod, 'PATH_INFO' => $path));
     $this->auth->expects($this->once())->method('hasIdentity')->will($this->returnValue($hasIdentity));
     $this->auth->expects($this->once())->method('getIdentity')->will($this->returnValue($identity));
     $app = new \Slim\Slim(array('debug' => false));
     $app->error(function (\Exception $e) use($app) {
         // Example of handling Auth Exceptions
         if ($e instanceof AuthException) {
             $app->response->setStatus($e->getCode());
             $app->response->setBody($e->getMessage());
         }
     });
     $app->get('/', function () {
     });
     $app->get('/member', function () {
     });
     $app->delete('/member/photo/:id', function ($id) {
     });
     $app->get('/admin', function () {
     });
     $app->map('/login', function () {
     })->via('GET', 'POST')->name('login');
     $app->add($this->middleware);
     ob_start();
     $app->run();
     ob_end_clean();
     $this->assertEquals($httpStatus, $app->response->status());
     $this->assertEquals($location, $app->response->header('location'));
 }
Example #2
0
 /**
  * Executa
  * @return null
  */
 static function run()
 {
     // Autoload baseado nos módulos carregados
     /*spl_autoload_register(function($className) {
     			$className = ltrim($className, '\\');
     			$fileName  = '';
     			$namespace = '';
     			if ($lastNsPos = strrpos($className, '\\')) {
     				$namespace = substr($className, 0, $lastNsPos);
     				$className = substr($className, $lastNsPos + 1);
     				$fileName  = str_replace('\\', DIRECTORY_SEPARATOR, $namespace) . DIRECTORY_SEPARATOR;
     			}
     			$fileName .= str_replace('_', DIRECTORY_SEPARATOR, $className) . '.php';
     			require $fileName;
     		});*/
     // Instanciando Slim
     //require __ROOT__ . '/vendor/slim/slim/Slim/Slim.php';
     //\Slim\Slim::registerAutoloader();
     $app = new \Slim\Slim();
     // Incluindo arquivos que devem vir antes dos routes
     foreach (self::$modules as $mod) {
         @(include "{$mod}/config.php");
         @(include "{$mod}/helpers.php");
         @(include "{$mod}/filter.php");
     }
     // Incluindo os routes
     foreach (self::$modules as $mod) {
         @(include "{$mod}/routes.php");
     }
     // Renderizando tudo
     $app->run();
 }
Example #3
0
 public function dispatch_api()
 {
     require_once 'lib/jsonp/jsonp.php';
     \Slim\Slim::registerAutoloader();
     $app = new \Slim\Slim();
     new \Voce\Thermal\v1\API($app);
     $app->run();
     exit;
 }
 public function testBestFormatWithPriorities()
 {
     \Slim\Environment::mock(array('ACCEPT' => 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'negotiation.priorities' => array('xml')));
     $s = new \Slim\Slim();
     $s->add(new ContentNegotiation());
     $s->run();
     $env = \Slim\Environment::getInstance();
     $bestFormat = $env['request.best_format'];
     $this->assertNotNull($bestFormat);
     $this->assertEquals('xml', $bestFormat);
 }
Example #5
0
 public static function start()
 {
     self::bootstrapErrorReporting();
     $app = new \Slim\Slim();
     self::bootstrapLogs();
     self::bootstrapSession();
     self::bootstrapDatabase();
     self::bootstrapViews();
     self::bootstrapRouting();
     return $app->run();
 }
 function init()
 {
     if (strstr($_SERVER['REQUEST_URI'], 'api/')) {
         define('SHORTINIT', true);
         $app = new \Slim\Slim();
         $app->setName('wp-elastic-api');
         new DocRoutes($app);
         new v1\Routes($app);
         $app->run();
         exit;
     }
 }
 /**
  * @param array $config
  * @return \Slim\Slim
  */
 public function dispatch($config)
 {
     \Slim\Environment::mock(array('REQUEST_METHOD' => 'HEAD', 'PATH_INFO' => '/'));
     $config['debug'] = false;
     // ignore pretty exceptions
     $slim = new \Slim\Slim($config);
     $manager = new \Slim\Middleware\SessionManager($slim);
     $manager->setDbConnection($this->capsule->getConnection());
     $session = new \Slim\Middleware\Session($manager);
     $slim->add($session);
     $slim->run();
     return $slim;
 }
Example #8
0
 public function run($root)
 {
     $this->routeStem = $root;
     // hook to correct the route, stripping off the Joomla route part
     $app = $this->slim;
     $app->hook('slim.before', function () use($app) {
         $app->environment['PATH_INFO'] = preg_replace('|/' . $this->routeStem . '|', '', $app->environment['PATH_INFO']);
     });
     $this->slim = $app;
     $this->_setupRoutes();
     //    echo '(bot)';
     $this->slim->run();
     //    echo '(eot)';
     exit;
 }
 /**
  * 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);
 }
Example #10
0
 public function __construct()
 {
     $view = new \Slim\Views\Twig();
     $app = new \Slim\Slim(array('debug' => DEBUG, 'view' => $view, 'templates.path' => HOME . '/' . APP . '/View'));
     $app->notFound(function () use($app) {
         $app->render('errors/404.html');
     });
     $controllerFactory = new \Core\ControllerFactory($app);
     // the class that builds the controllers
     $view->parserExtensions = array(new \MyTwigExtension($controllerFactory));
     $mainRoute = '/';
     if (!empty(SUB_FOLDER)) {
         // is the whole site in a subdirectory?
         $mainRoute .= SUB_FOLDER . '(/)';
     }
     $checkQueries = function ($q) {
         // our queries must be numerical for security's sake
         if (!empty($q)) {
             if (!is_numeric($q)) {
                 return false;
             }
             if ($q <= 0) {
                 return false;
             }
         }
         return true;
     };
     $app->group($mainRoute, function () use($app, $checkQueries, $controllerFactory) {
         // the admin route
         $app->map(ADMIN_FOLDER . '(/)(:controller)(/)(:action)(/)(:query)(/)', function ($controller = '', $action = '', $query = '') use($app, $checkQueries, $controllerFactory) {
             if (false === $checkQueries($query)) {
                 $app->notFound();
             } else {
                 $controllerFactory->buildController($controller, $action, true, $query);
             }
         })->via('POST', 'GET');
         // front end routing
         $app->map('(:controller)(/)(:action)(/)(:query)(/)(:query2)(/)', function ($controller = '', $action = '', $query = '', $query2 = '') use($app, $checkQueries, $controllerFactory) {
             if (false === $checkQueries($query) || false === $checkQueries($query2)) {
                 $app->notFound();
             } else {
                 $controllerFactory->buildController($controller, $action, false, $query, $query2);
             }
         })->via('POST', 'GET');
     });
     $app->run();
     // run Slim Application
 }
 public function run()
 {
     $app = new \Slim\Slim();
     $this->app = $app;
     GetAllHeadersService::fixMissingFunction();
     $app->add(new \Widgeto\Middleware\Authorization(getallheaders(), array('^\\/$' => 'GET', '^\\/[^.]*.html$' => 'GET', '^\\/rest\\/login\\/$' => 'POST')));
     \dibi::connect(DatabaseConfigService::getConfig());
     \dibi::getSubstitutes()->{''} = getenv("TABLE_PREFIX");
     new \Widgeto\Rest\LoginRest($app);
     new \Widgeto\Rest\LogoutRest($app);
     new \Widgeto\Rest\PageRest($app);
     new \Widgeto\Rest\TemplateRest($app);
     new \Widgeto\Rest\FileRest($app);
     new \Widgeto\Rest\UserRest($app);
     new \Widgeto\Rest\HomeRest($app);
     $app->run();
 }
    /**
     * 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 #13
0
 /**
  * REST actions
  *
  * This function contains the REST actions with the assignments to
  * the functions.
  *
  * @param string[] $_argv Konsolenparameter, null = leer
  */
 public function __construct($_argv)
 {
     if ($_argv != null) {
         // es gibt Konsolenparameter, diese werden nun $_POST zugewiesen,
         // sodass der Installationsassistent sie verwenden kann
         array_shift($_argv);
         foreach ($_argv as $arg) {
             $_POST[$arg] = 'OK';
         }
         $this->CallInstall(true);
         return;
     }
     // initialize slim
     $app = new \Slim\Slim(array('debug' => true));
     $app->contentType('text/html; charset=utf-8');
     // POST,GET showInstall
     $app->map('(/)', array($this, 'CallInstall'))->via('POST', 'GET', 'INFO');
     // POST,GET showInstall
     $app->map('/checkModulesExtern(/)', array($this, 'checkModulesExtern'))->via('POST', 'GET', 'INFO');
     // run Slim
     $app->run();
 }
Example #14
0
// Selvitetään, missä kansiossa index.php on
$script_name = $_SERVER['SCRIPT_NAME'];
$explode = explode('/', $script_name);
if ($explode[1] == 'index.php') {
    $base_folder = '';
} else {
    $base_folder = $explode[1];
}
// Määritetään sovelluksen juuripolulle vakio BASE_PATH
define('BASE_PATH', '/' . $base_folder);
// Luodaan uusi tai palautetaan olemassaoleva sessio
if (session_id() == '') {
    session_start();
}
// Asetetaan vastauksen Content-Type-otsake, jotta ääkköset näkyvät normaalisti
header('Content-Type: text/html; charset=utf-8');
// Otetaan Composer käyttöön
require 'vendor/autoload.php';
$routes = new \Slim\Slim();
$routes->add(new \Zeuxisoo\Whoops\Provider\Slim\WhoopsMiddleware());
$routes->get('/tietokantayhteys', function () {
    DB::test_connection();
});
function twig_path_for($route_name, $args = array())
{
    return \Slim\Slim::getInstance()->urlFor($route_name, $args);
}
// Otetaan reitit käyttöön
require 'config/routes.php';
$routes->run();
 /**
  * Test parses request body based on media-type only, disregarding
  * any extra content-type header parameters
  */
 public function testParsesRequestBodyWithMediaType()
 {
     \Slim\Environment::mock(array('REQUEST_METHOD' => 'POST', 'CONTENT_TYPE' => 'application/json; charset=ISO-8859-4', 'CONTENT_LENGTH' => 13, 'slim.input' => '{"foo":"bar"}'));
     $s = new \Slim\Slim();
     $s->add(new \Slim\Middleware\ContentTypes());
     $s->run();
     $body = $s->request()->getBody();
     $this->assertTrue(is_array($body));
     $this->assertEquals('bar', $body['foo']);
 }
Example #16
0
<?php

require "easygallery.php";
require "Slim/Slim.php";
\Slim\Slim::registerAutoloader();
$galleryApp = new \Slim\Slim();
$galleryApp->get('/gallery', function () {
    echo json_encode(findfolders());
});
$galleryApp->run();
?>
	
Example #17
0
<?php

/**
 * Copyright (C) 2015 FeatherBB
 * based on code by (C) 2008-2015 FluxBB
 * and Rickard Andersson (C) 2002-2008 PunBB
 * License: http://www.gnu.org/licenses/gpl.html GPL version 2 or higher
 */
// Start a session for flash messages
session_cache_limiter(false);
session_start();
error_reporting(E_ALL);
// Let's report everything for development
ini_set('display_errors', 1);
// Load Slim Framework
require 'vendor/autoload.php';
// Instantiate Slim and add CSRF
$feather = new \Slim\Slim();
$feather->add(new \FeatherBB\Middleware\Csrf());
$feather_settings = array('config_file' => 'featherbb/config.php', 'cache_dir' => 'cache/', 'debug' => 'all');
// 3 levels : false, info (only execution time and number of queries), and all (display info + queries)
$feather->add(new \FeatherBB\Middleware\Auth());
$feather->add(new \FeatherBB\Middleware\Core($feather_settings));
// Load the routes
require 'featherbb/routes.php';
// Run it, baby!
$feather->run();
Example #18
0
        //if (isset($_SESSION['isLoggedIn'])){
        //if ($_SESSION['isLoggedIn'] == true){ //do i need to check if this session variable exists first?
        if (loggedIn()) {
            $conn = dbConnect();
            $params = array($_SESSION['UserID']);
            $query = $conn->prepare("SELECT *\n\t\t                    FROM Accounts\n\t\t                    WHERE UserID = ?");
            $query->execute($params);
            $getUser = $query->fetch(PDO::FETCH_ASSOC);
            if ($getUser != null) {
                //user found
                //$userObj = new userObj($getUser['UserName'],$getUser['FirstName'],$getUser['LastName'],$getUser['EmailAddress'],$getUser['PhoneNumber'],$getUser['UserId'],$getUser['RoleID'],$getUser['LanguagePreference']);
                //get notifications
                //$rtnObj->setUser($userObj);
                $rtnObj->setStatus(0);
                $rtnObj->setSuccessStatus('LoggedIn');
                $rtnObj->setMessage('LoggedIn');
                $rtnObj->sessionUserID = $_SESSION['UserID'];
            }
            /**/
            //echo "is true";
        }
        //}
        //echo "is set";
        //}
        echo json_encode($rtnObj);
    } catch (Exception $e) {
        echo $e->getMessage();
    }
}
$slimApp->run();
Example #19
0
 *      summary="Get information about used plugins",
 *      notes="",
 *      method="GET",
 *      type="array",
 *      nickname="getDevAACPlugins"
 *   )
 *  )
 * )
 */
$DevAAC->get(ROUTES_API_PREFIX . '/plugins', function () use($DevAAC) {
    $DevAAC->response->setBody(json_encode($DevAAC->plugins), JSON_PRETTY_PRINT);
    $DevAAC->response->headers->set('Content-Type', 'application/json');
});
//////////////////////////////////////////////////////////////////////
// all done, any code after this call will not matter to the request
$DevAAC->run();
////////////////////////////// MISC /////////////////////////////////
function xml2array($xmlObject, $out = array())
{
    foreach ((array) $xmlObject as $index => $node) {
        $out[$index] = is_object($node) || is_array($node) ? xml2array($node) : $node;
        if (is_array($out[$index]) && array_key_exists('@attributes', $out[$index])) {
            foreach ($out[$index]['@attributes'] as $key => $value) {
                $out[$index][$key] = is_numeric($value) ? floatval($value) : $value;
            }
            unset($out[$index]['@attributes']);
        }
    }
    return $out;
}
// http://shiplu.mokadd.im/95/convert-little-endian-to-big-endian-in-php-or-vice-versa/
Example #20
0
        $plist = new \CFPropertyList\CFPropertyList();
        $plist->parse($body);
        $message = $plist->toArray();
        $message_type = $message["MessageType"];
        if ($message_type == "Authenticate") {
            // TODO: authentication
            // grab our UUID and create/update our data
            $udid = $message["UDID"];
            $device = array();
            $device["udid"] = $udid;
            // we just return an 'OK' here
            create_device($device);
            // now, send back a response
            $res_plist = new \CFPropertyList\CFPropertyList();
            $res_plist->add($dict = new \CFPropertyList\CFDictionary());
            echo $res_plist->toXML();
        } elseif ($message_type == "TokenUpdate") {
            update_device_token($message);
            $res_plist = new \CFPropertyList\CFPropertyList();
            $res_plist->add($dict = new \CFPropertyList\CFDictionary());
            echo $res_plist->toXML();
        } elseif ($message_type == "CheckOut") {
            check_out_device($message);
            // the device is leaving our MDM zone, so we need to set the values for
            // this in the correct place
        }
    }
    // $slim->render('index.php');
});
$slim->run();
Example #21
0
 /**
  * Test default error handler logs the error when debug is false.
  *
  * Pre-conditions:
  * Invoked app route calls default error handler;
  *
  * Post-conditions:
  * Error log is called
  */
 public function testDefaultHandlerLogsTheErrorWhenDebugIsFalse()
 {
     $s = new \Slim\Slim(array('debug' => false));
     $s->container->singleton('log', function ($c) {
         return new EchoErrorLogger();
     });
     $s->get('/bar', function () use($s) {
         throw new \InvalidArgumentException('my specific error message');
     });
     ob_start();
     $s->run();
     $output = ob_get_clean();
     $this->assertTrue(strpos($output, 'InvalidArgumentException:my specific error message') !== false);
 }
Example #22
0
$rest->post('/sales/', function () use($rest) {
    include_once API_ROOT . "/sales.inc";
    sales_add();
});
// Edit Sales
$rest->put('/sales/:trans_no/:trans_type', function ($trans_no, $trans_type) use($rest) {
    include_once API_ROOT . "/sales.inc";
    sales_edit($trans_no, $trans_type);
});
// Cancel Sales
$rest->delete('/sales/:branch_id/:uuid', function ($branch_id, $uuid) use($rest) {
    include_once API_ROOT . "/sales.inc";
    sales_cancel($branch_id, $uuid);
});
// All Sales
$rest->get('/sales/:trans_type/', function ($trans_type) use($rest) {
    global $req;
    include_once API_ROOT . "/sales.inc";
    $page = $req->get("page");
    if ($page == null) {
        sales_all($trans_type);
    } else {
        // If page = 1 the value will be 0, if page = 2 the value will be 1, ...
        $from = --$page * RESULTS_PER_PAGE;
        sales_all($trans_type, $from);
    }
});
// ------------------------------- Sales Order Entry -------------------------------
// Init API
$rest->run();
Example #23
0
$webApp->add(new \Slim\Middleware\HttpBasicAuthentication(['users' => [HTTP_USER => HTTP_PASSWORD], 'realm' => 'taski']));
$webApp->post('/api/add-task', function () use($webApp) {
    $taski = new \Taski\Taski();
    $app = $webApp->request->post('app');
    $params = $webApp->request->post('params');
    if (empty($params)) {
        $params = '';
    }
    if ($taski->app_defined($app)) {
        $taski->execute($app, urldecode($params), 'Task enqueued');
    } else {
        $webApp->response->headers->set('Content-Type', 'application/json');
        echo json_encode(array('result' => 'Error, application is not a known application'));
        $webApp->response()->status(500);
    }
});
$webApp->get('/api/get-tasks', function () use($webApp) {
    $taski = new \Taski\Taski();
    $tasks = $taski->get_tasks();
    $webApp->response->headers->set('Content-Type', 'application/json');
    echo json_encode($tasks);
});
$webApp->get('/', function () use($webApp) {
    $taski = new \Taski\Taski();
    $tasks = $taski->get_tasks();
    $apps = $taski->get_apps();
    $data = array('tasks' => $tasks, 'apps' => $apps);
    include 'frontend.php';
});
$webApp->run();
Example #24
0
 private function runAppPreFlight($action, $actionName, $mwOptions = NULL, $headers = array())
 {
     \Slim\Environment::mock(array('REQUEST_METHOD' => 'OPTIONS', 'SERVER_NAME' => 'localhost', 'SERVER_PORT' => 80, 'ACCEPT' => 'application/json', 'SCRIPT_NAME' => '/index.php', 'PATH_INFO' => '/' . $actionName));
     $app = new \Slim\Slim();
     $app->setName($actionName);
     $mw = function () {
         // Do nothing
     };
     if (isset($mwOptions)) {
         if (is_callable($mwOptions)) {
             $mw = $mwOptions;
         } else {
             $mwOptions['appName'] = $actionName;
             $mw = \CorsSlim\CorsSlim::routeMiddleware($mwOptions);
         }
     }
     $app->options('/:name', $mw, function ($name) use($app, $action) {
     });
     $app->delete('/:name', $mw, 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" => "DELETE", "name" => $name)));
     });
     foreach ($headers as $key => $value) {
         $app->request->headers()->set($key, $value);
     }
     $app->run();
     return $app;
 }
<?php

include 'dbConfig.php';
require 'Slim/Slim.php';
\Slim\Slim::registerAutoloader();
$slim_app = new \Slim\Slim();
$slim_app->get('/showEmp', 'loadUsers');
$slim_app->post('/newUser', 'newUser');
$slim_app->delete('/deleteUser/:empid', 'deleteUser');
$slim_app->post('/editEmp', 'editEmp');
$slim_app->get('/loadEditUser/:eid', 'loadEditUser');
$slim_app->run();
function loadUsers()
{
    $sql = "SELECT id,name,dob,dept,email,phone,address FROM employees ORDER BY id asc";
    try {
        $db = getDB();
        $stmt = $db->query($sql);
        $users = $stmt->fetchAll(PDO::FETCH_OBJ);
        $db = null;
        echo json_encode($users);
    } catch (PDOException $e) {
        echo '{"error":{"text":' . $e->getMessage() . '}}';
    }
}
function newUser()
{
    $request = \Slim\Slim::getInstance()->request();
    $insert = json_decode($request->getBody());
    $sql = "INSERT INTO employees (id, name ,dob, dept, email, phone, address) VALUES (:id, :name, :dob, :dept, :email, :phone, :address)";
    try {
Example #26
0
            $time = explode(",", $value['time_showing']);
            $time = str_replace("(", "", $time);
            $time = str_replace(")", "", $time);
            $time_showing = array_combine($days, $time);
            $movie_group = array('title' => $value['movie_title'], 'year' => $value['year'], 'genre' => $value['genre'], 'synopsis' => $value['synopsis'], 'actors' => $value['actors'], 'imdb rating' => $value['imdb_rating'], 'imdb votes' => $value['imdb_votes'], 'poster' => $value['poster'], 'time showing' => $time_showing);
            array_push($movies, $movie_group);
        }
        // $app->response()->header('Content-Type', 'application/json');
        //
        header("Content-type: application/json");
        echo json_encode(array("Anga Sky Movies" => $movies));
    };
    $splited(R::exportAll($movies));
});
$app->response()->header('Content-Type', 'application/json');
$memoize = function ($func) {
    return function () use($func) {
        static $cache = [];
        $args = func_get_args();
        $key = md5(serialize($args));
        if (!isset($cache[$key])) {
            $cache[$key] = call_user_func_array($func, $args);
        }
        return $cache[$key];
    };
};
if (array_key_exists("key", $_GET) && $_GET['key'] === $key) {
    $memoize($app->run());
} else {
    require "404.html";
}
Example #27
0
        if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] == True) {
            foreach ($oCreds->Admins as $sEmail) {
                if ($sEmail == $oUserInfo->email) {
                    $_SESSION['isAdmin'] = True;
                    ChromePhp::info("Admin Login success");
                    break;
                }
            }
        } else {
            $oApp->render('error.phtml');
        }
    }
    $oApp->redirect('/');
});
/***
 * Inner functions
***/
function getUserType()
{
    if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] == True) {
        if (isset($_SESSION['isAdmin']) && $_SESSION['isAdmin'] == True) {
            return 'admin';
        } else {
            return 'user';
        }
    } else {
        return '';
    }
}
$oApp->run();
Example #28
0
    $email = $json->{'email'};
    $password = sha1($json->{'password'});
    $role = $json->{'role'};
    try {
        $sql0 = "select id from user order by id desc limit 1";
        $db = getConnection();
        $stmt = $db->query($sql0);
        $users = $stmt->fetchAll(PDO::FETCH_OBJ);
        $idInsert = $users[0]->id + 1;
        $sql = "INSERT INTO user VALUE('{$idInsert}','{$lastname}','{$firstname}','{$email}','{$password}','{$role}') ";
        $dbCon = getConnection();
        $stmt = $dbCon->prepare($sql);
        $stmt->execute();
        $dbCon = null;
        echo '{"status": 200,"message": "' . $idInsert . '"}';
    } catch (PDOException $e) {
        $application->response->setStatus(500);
        echo '{"status": 500,"message": "' . $e->getMessage() . '"}';
    }
}
$application->run();
function getConnection()
{
    $dbhost = "localhost";
    $dbuser = "******";
    $dbpass = "";
    $dbname = "examplerest";
    $dbh = new PDO("mysql:host={$dbhost};dbname={$dbname}", $dbuser, $dbpass, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    return $dbh;
}
Example #29
0
//------------------------------------------------------------------------
//------------------------------------------------------------------------
//------------------------------------------------------------------------
$app->get('/getShopByUserId', function () use($app) {
    $db = getDB();
    $user = json_decode($app->request->getBody(), true);
    $shop = array();
    $stt = "SELECT tblShop.id, tblShop.transactionValue,  ";
    $stt = $stt . " tblCart.gameIdFk, tblGame.name, tblGame.console, ";
    $stt = $stt . " tblGame.photoLink, tblCart.transactionValue as gameValue ";
    $stt = $stt . " FROM tblShop ";
    $stt = $stt . " INNER JOIN tblShopCart ON tblShopCart.id = tblCart.shopIdFk ";
    $stt = $stt . " INNER JOIN tblCart ON tblCart.id = tblShopCart.cartIdFk ";
    $stt = $stt . " INNER JOIN tblGame ON tblGame.id = tblCart.gameIdFk ";
    $stt = $stt . " WHERE tblShop.userIdFk = " . $user['id'] . " ; ";
    $result = mysql_query($stt, $db);
    if ($result) {
        while ($row = mysql_fetch_array($result)) {
            $shop[] = array('id' => $row['id'], 'transactionValue' => $row['transactionValue'], 'gameIdFk' => $row['gameIdFk'], 'name' => $row['name'], 'console' => $row['console'], 'photoLink' => $row['photoLink'], 'gameValue' => $row['gameValue']);
        }
    } else {
        echo 'FAIL';
    }
    $app->response()->header('Content_type', 'application/json');
    echo json_encode($shop);
});
//------------------------------------------------------------------------
//------------------------------------------------------------------------
//------------------------------------------------------------------------
$app->run();
Example #30
0
 public function testKeepFlashForNextRequest()
 {
     $_SESSION['slim.flash'] = array('info' => 'Foo');
     $s = new \Slim\Slim();
     $s->get('/bar', function () use($s) {
         $s->flashKeep();
     });
     $s->run();
     $this->assertEquals('Foo', $_SESSION['slim.flash']['info']);
 }