Exemplo n.º 1
0
 function run()
 {
     $config = parse_ini_file('../.config');
     $this->setUpDb();
     $showErrors = isset($config['showErrors']) ? $config['showErrors'] : false;
     $configuration = ['settings' => ['displayErrorDetails' => $showErrors]];
     $c = new \Slim\Container($configuration);
     // create new Slim instance
     $app = new \Slim\App($c);
     // create new Slim instance
     //$app = new \Slim\App();
     $app->db = $this->database;
     $this->flashDB(false);
     $app->auth = false;
     $app->user = '';
     $app->register = $config['registerActive'];
     $app->add(function ($request, $response, $next) use(&$app) {
         if (isset($_SESSION['userID'])) {
             $app->auth = true;
             $app->user = $_SESSION['username'];
         }
         $response = $next($request, $response);
         return $response;
     });
     $container = $app->getContainer();
     $container['view'] = function ($c) {
         // templates location and a settings array
         $view = new \Slim\Views\Twig('../templates', ['cache' => '../cache', 'auto_reload' => true, 'debug' => true]);
         // Instantiate and add Slim specific extension
         $view->addExtension(new Slim\Views\TwigExtension($c['router'], $c['request']->getUri()));
         return $view;
     };
     $route = new Routes($app);
     $app = $route->run($app);
     $this->app = $app;
     // Run app
     $this->app->run();
 }
Exemplo n.º 2
0
 public function run()
 {
     $configuration = ['settings' => ['displayErrorDetails' => false]];
     $c = new \Slim\Container($configuration);
     $c['notFoundHandler'] = function ($c) {
         return function ($request, $response) use($c) {
             return $c['response']->withStatus(404)->withHeader('Content-type', 'application/json')->write(json_encode(array('status' => 404, 'error' => 'not_found', 'pretty_error' => 'Could not find the specified endpoint.'), JSON_PRETTY_PRINT));
         };
     };
     $c['errorHandler'] = function ($c) {
         return function ($request, $response) use($c) {
             return $c['response']->withStatus(500)->withHeader('Content-type', 'application/json')->write(json_encode(array('status' => 404, 'error' => 'internal_error', 'pretty_error' => 'An internal error has occured, please contact the site administrator.'), JSON_PRETTY_PRINT));
         };
     };
     $app = new \Slim\App($c);
     $app->add(new AuthenticationMiddleware());
     $app->get('/oauth/v2/authorize', 'PleioRest\\Controllers\\Authentication::authorize');
     $app->post('/oauth/v2/token', 'PleioRest\\Controllers\\Authentication::getToken');
     $app->get('/api/users/me', 'PleioRest\\Controllers\\User:me');
     $app->post('/api/users/me/register_push', 'PleioRest\\Controllers\\User:registerPush');
     $app->post('/api/users/me/deregister_push', 'PleioRest\\Controllers\\User:deregisterPush');
     $app->post('/api/users/me/generate_token', 'PleioRest\\Controllers\\User:generateToken');
     $app->get('/api/users/me/login_token', 'PleioRest\\Controllers\\User:loginToken');
     $app->get('/api', 'PleioRest\\Controllers\\Version:getVersion');
     $app->get('/api/doc', 'PleioRest\\Controllers\\Documentation:getDocumentation');
     $app->get('/api/doc/swagger', 'PleioRest\\Controllers\\Documentation:getSwagger');
     $app->get('/api/sites', 'PleioRest\\Controllers\\Sites:getAll');
     $app->get('/api/sites/mine', 'PleioRest\\Controllers\\Sites:getMine');
     $app->get('/api/groups', 'PleioRest\\Controllers\\Groups:getAll');
     $app->get('/api/groups/mine', 'PleioRest\\Controllers\\Groups:getMine');
     $app->get('/api/groups/{guid}/activities', 'PleioRest\\Controllers\\Activities:getGroup');
     $app->post('/api/groups/{guid}/activities/mark_read', 'PleioRest\\Controllers\\Activities:markRead');
     $app->get('/api/groups/{guid}/events', 'PleioRest\\Controllers\\Events:getGroup');
     $app->get('/api/groups/{guid}/members', 'PleioRest\\Controllers\\Members:getGroup');
     $app->get('/api/groups/{guid}/files', 'PleioRest\\Controllers\\Files:getGroup');
     $app->run();
 }
Exemplo n.º 3
0
    // echo 'Hello, world!';
    $response->write('Hello, ' . $args['name'] . '!');
    return $response;
})->setName('hello-world');
// 3 // Twig stuff
$app->get('/zorro/{name:[A-Za-z]+}', function ($request, $response, $args) {
    // Remember, $this is the $app.
    $template = $this->getContainer()->get('twig')->loadTemplate('layout.php');
    return $response->write($template->render(['content' => 'Hello bello mellow yellow!']));
})->setName('zorro');
/**
 * middleware
 */
$app->add(function ($request, $response, $next) {
    $response->write('BEFORE');
    $response = $next($request, $response);
    $response->write('AFTER');
    return $response;
});
// run
$app->run();
/**
 * Profile
 */
if (defined('APP_PROFILE')) {
    echo '<hr/>';
    print_r('time     : ' . round(microtime(true) - APP_START_TIME, 4) . '<br/>');
    print_r('mem      : ' . round((memory_get_usage() - APP_START_MEM) / 1024 / 1024, 4) . '<br/>');
    print_r('mem peak : ' . round((memory_get_peak_usage() - APP_START_MEM) / 1024 / 1024, 4) . '<br/>');
}
// eof
Exemplo n.º 4
0
<?php

require 'vendor/autoload.php';
require 'config/env.php';
require 'config/mysql.php';
require 'config/redis.php';
// Create Slim app
$app = new \Slim\App(['settings' => ['debug' => true]]);
// Add whoops to slim because its helps debuggin' and is pretty.
$app->add(new \Zeuxisoo\Whoops\Provider\Slim\WhoopsMiddleware());
// Fetch DI Container
$container = $app->getContainer();
// Instantiate and add Slim specific extension
$view = new \Slim\Views\Twig(__DIR__ . '/views', ['cache' => $container->get('settings')['debug'] ? false : __DIR__ . '/cache']);
$view->addExtension(new Slim\Views\TwigExtension($container->get('router'), $container->get('request')->getUri()));
// Register Twig View helper
$container->register($view);
// Write some default variables available to every template
$view->offsetSet('realtime_url', $environment['REALTIME_URL']);
$view->offsetSet('current_watts', is_numeric($redis->get('owlintuition.watts')) ? $redis->get('owlintuition.watts') : '???');
$app->get('/', function (\Slim\Http\Request $request, \Slim\Http\Response $response, $args) {
    header("Location: /redis");
    exit;
});
$app->get('/redis', function (\Slim\Http\Request $request, \Slim\Http\Response $response, $args) {
    global $redis;
    $keys = $redis->keys('*');
    $redisKeys = [];
    foreach ($keys as $key) {
        $redisKeys[$key] = ['key' => $key, 'value' => $redis->get($key)];
    }
Exemplo n.º 5
0
$capsule = new Capsule();
$capsule->addConnection($config['parameters']);
$capsule->setAsGlobal();
$capsule->bootEloquent();
$container = new \Slim\Container(['settings' => ['displayErrorDetails' => true]]);
//modification de l'erreur 404
$container['notFoundHandler'] = function ($container) {
    return function ($request, $response) use($container) {
        return $container['response']->withJson(array("status" => array("error" => "not found")), 404);
    };
};
//modification de l'erreur 500
$container['errorHandler'] = function ($container) {
    return function ($request, $response, $exception) use($container) {
        return $container['response']->withJson(array("status" => array("error" => ['code' => $exception->getCode(), 'message' => $exception->getMessage(), 'file' => $exception->getFile(), 'line' => $exception->getLine(), 'trace' => explode("\n", $exception->getTraceAsString())])), 500);
    };
};
$app = new Slim\App($container);
$app->add(new \Slim\Middleware\HttpBasicAuthentication(['path' => ['/command/', '/product/', '/user/', '/banniere/'], 'secure' => false, 'relaxed' => $config['parameters']['hosts_allows'], 'users' => $config['parameters']['api_users']]));
//ajout des routes
require 'routes/product.php';
require 'routes/command.php';
require 'routes/notification.php';
require 'routes/user.php';
require 'routes/login.php';
require 'routes/other.php';
//redirection vers la doc
$app->get('/', function ($request, $response) use($app) {
    return $response->withRedirect('doc/');
});
$app->run();
Exemplo n.º 6
0
require '../vendor/autoload.php';
use Slim\Http\Request;
use Slim\Http\Response;
$app = new Slim\App();
$container = $app->getContainer();
$container['settings']['displayErrorDetails'] = true;
$container['view'] = function ($c) {
    $view = new \Slim\Views\Twig('../templates', ['cache' => false]);
    // Instantiate and add Slim specific extension
    $view->addExtension(new \Slim\Views\TwigExtension($c['router'], $c['request']->getUri()));
    return $view;
};
$app->add(function (Request $request, Response $response, $next) {
    if ($request->getUri()->getScheme() !== 'https') {
        $uri = $request->getUri()->withScheme("https")->withPort(null);
        return $response->withRedirect((string) $uri);
    } else {
        return $next($request, $response);
    }
});
$app->get('/', function (Request $request, Response $response, $args) {
    return $this->view->render($response, "index.twig", ["title" => "Welcome!"]);
});
$app->get('/articles/slim-intro[.html]', function (Request $request, Response $response, $args) {
    return $this->view->render($response, "slim-intro.twig", ["title" => "Slim Introduction"]);
});
$app->get('/articles/php-app-architecture[.html]', function (Request $request, Response $response, $args) {
    return $this->view->render($response, "php-app-architecture.twig", ["title" => "PHP App Architecture"]);
});
$app->run();
Exemplo n.º 7
0
<?php

require 'vendor/autoload.php';
require 'config/config.php';
use Illuminate\Database\Capsule\Manager as Capsule;
$capsule = new Capsule();
$capsule->addConnection(array('driver' => DB_SGBD, 'host' => DB_HOST, 'database' => DB_BASE, 'username' => DB_USER, 'password' => DB_PASSWORD, 'charset' => DB_CHARSET, 'collation' => DB_COLLATION, 'prefix' => DB_PREFIX));
$capsule->setAsGlobal();
$capsule->bootEloquent();
$app = new Slim\App();
$app->add(new Slim\Middleware\HttpBasicAuthentication(["path" => "/", "realm" => "Protected", "users" => [API_USER => API_PASSWORD]]));
//ajout des routes
require 'routes/product.php';
require 'routes/command.php';
require 'routes/notification.php';
require 'routes/user.php';
require 'routes/other.php';
//redirection vers la doc
$app->get('/', function ($request, $response) use($app) {
    return $response->withRedirect('doc/');
});
$app->run();
Exemplo n.º 8
0
        if (count($miss) >= 1) {
            $r->result = $miss[0];
        }
    }
    $res->getBody()->write(json_encode($r));
    return $res;
});
$app->add(function ($req, $res, $next) {
    // CORS
    if (isset($_SERVER['HTTP_ORIGIN'])) {
        header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
        header('Access-Control-Allow-Headers: X-Requested-With');
    }
    if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
        if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD'])) {
            header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
        }
        if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS'])) {
            header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
        }
        exit(0);
    }
    $response = $next($req, $res);
    return $response;
});
$app->add(function ($req, $res, $next) {
    // JSON and JSONP
    header('Content-Type: application/json');
    if (isset($_GET['callback'])) {
        echo $_GET['callback'] . '(';
    }
    $response = $next($req, $res);
Exemplo n.º 9
0
<?php

require_once __DIR__ . "/../config.php";
require_once __DIR__ . '/../vendor/autoload.php';
use Psr7Middlewares\Middleware;
$app = new \Slim\App(new \App\Lib\AppContainer());
$app->add(Middleware::ResponseTime());
$app->add(Middleware::TrailingSlash());
require_once 'routes.php';
$app->run();
Exemplo n.º 10
0
    return array('code' => '200', 'error' => '', 'token' => '', 'result' => '');
};
$container['notFoundHandler'] = function ($c) {
    return function ($request, $response) use($c) {
        $notFoundResponse = json_encode(array('code' => 400, 'error' => 'Bad Request', 'result' => null));
        return $c['response']->withStatus(400)->withHeader('Content-Type', 'application/json')->write($notFoundResponse);
    };
};
if (IS_PRODUCTION_SERVER == "true") {
    $container['errorHandler'] = function ($c) {
        return function ($request, $response) use($c) {
            $notFoundResponse = json_encode(array('code' => 500, 'error' => 'Internal Server Error', 'result' => null));
            return $c['response']->withStatus(500)->withHeader('Content-Type', 'application/json')->write($notFoundResponse);
        };
    };
}
// Check Access-Levels
$app->add(new Zawana\Middleware\ApiMiddleware());
require_once FOLDER_CONFIG . 'routing.php';
/**
 * debug arrays
 */
function pre($arr, $debug = 0)
{
    echo "<pre>";
    print_r($arr);
    echo "</pre>";
    if ($debug == 1) {
        die;
    }
}
Exemplo n.º 11
0
require '../vendor/autoload.php';
$app = new \Slim\App();
// Register with container
$container = $app->getContainer();
$container['csrf'] = function ($c) {
    $guard = new \Slim\Csrf\Guard();
    $guard->setFailureCallable(function ($request, $response, $next) {
        $request = $request->withAttribute('csrf_status', false);
        var_dump($request);
        return $next($request, $response);
    });
    return $guard;
};
// Register middleware for all routes
// If you are implementing per-route checks you must not add this
$app->add($container->get('csrf'));
$app->get('/', function ($request, $response, $args) {
    $response->write("Welcome to Slim!");
    return $response;
});
$app->get('/hello[/{name}]', function ($request, $response, $args) {
    $response->write("Hello, " . $args['name']);
    return $response;
})->setArgument('name', 'World!');
$app->any('/test', function () use($app) {
    //GET
    $allGetVars = $request->getQueryParams();
    print_r($allGetVars);
    foreach ($allGetVars as $key => $param) {
        //GET parameters list
    }
Exemplo n.º 12
0
        $comment = $request->getParsedBody();
        $db = $this->sql;
        if ($db) {
            try {
                $result = $db->insert('comments', ['post_id' => $comment['post_id'], 'mem_id' => $comment['mem_id'], 'content' => $comment['content'], 'comment_date' => $comment['comment_date']]);
                $comment['id'] = $db->getId($result);
                $response->getBody()->write(json_encode($comment));
                return $response->withStatus(201);
            } catch (Exception $e) {
                return $response->withStatus(409, $e->getMessage);
            }
        }
        return $response->withStatus(404, 'Mmmhh... We couldn\'t connect to our server somehow :/ Please try again or contact your administrator.');
    });
    $this->delete('/comment{id}', function ($request, $response, $args) {
        $commentId = $args['id'];
        $db = $this->sql;
        if ($db) {
            try {
                $result = $db->query('call deleteComment(?)', [$commentId]);
                $response->getBody()->write(json_encode($commentId));
                return $response->withStatus(200);
            } catch (Exception $e) {
                return $response->withStatus(404, 'Oops! It seems like we couldn\'t delete this comment... strange. Maybe it already has been deleted? Refresh the page to find out!');
            }
        }
        return $response->withStatus(404, 'Mmmhh... We couldn\'t connect to our server somehow :/ Please try again or contact your administrator.');
    });
});
$app->add(new ActivityMiddleware())->add(new MemberAuthorizationMiddleware())->add(new AdminAuthorizationMiddleware())->add(new AuthenticatedMiddleware())->add(new SessionMiddleware())->add(new SessionInitMiddleware());
$app->run();
Exemplo n.º 13
0
    $file = __DIR__ . $_SERVER['REQUEST_URI'];
    if (is_file($file)) {
        return false;
    }
}
require __DIR__ . '/../vendor/autoload.php';
session_start();
$yaml = new Parser();
try {
    $configuration = $yaml->parse(file_get_contents(__DIR__ . '/../app/config/config.yml'));
} catch (ParseException $e) {
    printf("Unable to parse the YAML string: %s", $e->getMessage());
}
$app = new \Slim\App($configuration);
// Register middlewares
$app->add(new HttpBasicAuthentication($configuration['basic_auth']));
$container = $app->getContainer();
// Register twig template service
$container['view'] = function ($c) {
    $settings = $c->get('settings');
    $twigOptions = $settings['view']['twig'];
    $twigOptions['cache'] = __DIR__ . $settings['view']['twig']['cache'];
    $view = new \Slim\Views\Twig(__DIR__ . $settings['view']['template_path'], $twigOptions);
    $view->addExtension(new \Slim\Views\TwigExtension($c->get('router'), $c->get('request')->getUri()));
    $view->addExtension(new Twig_Extension_Debug());
    $view->addExtension(new DayOfWeekExtension());
    return $view;
};
// Register flash message service
$container['flash'] = function ($c) {
    return new \Slim\Flash\Messages();
Exemplo n.º 14
0
{
    $str = ucwords($str, $delimiter);
    $str = str_replace($delimiter, '', $str);
    return $str;
}
/**
 * Permanently redirect paths with a trailing slash to their non-trailing
 * counterpart.
 *
 * @see http://www.slimframework.com/docs/cookbook/route-patterns.html
 */
$app->add(function (Request $request, Response $response, callable $next) {
    $uri = $request->getUri();
    $path = $uri->getPath();
    if ($path != '/' && substr($path, -1) == '/') {
        $uri = $uri->withPath(substr($path, 0, -1));
        return $response->withRedirect((string) $uri, 301);
    }
    return $next($request, $response);
});
/**
 * Handle request and process response.
 *
 * Loads controller based endpoint and calls the controller's method based on the
 * request method.
 *
 */
$app->any('/[{controller}[/{segments:.+}]]', function (Request $request, Response $response, $args) {
    if (!count($args)) {
        $args['controller'] = strtolower(\App\Controller\Controller::DEFAULT_CONTROLLER);
    }
Exemplo n.º 15
0
<?php

/**
 * app.php
 */
require_once __DIR__ . "/../config.php";
require_once __DIR__ . '/../vendor/autoload.php';
use Psr7Middlewares\Middleware;
$app = new \Slim\App(new \App\Lib\AppContainer(['settings' => ['displayErrorDetails' => true]]));
$app->add(Middleware::responseTime());
$app->add(Middleware::TrailingSlash());
$app->add(Middleware::BasicAuthentication()->users(['test' => '1234']));
require_once 'routes.php';
$app->run();
Exemplo n.º 16
0
    // We know the list id and the categiry id so lets use it
    return $container['mailchimp']->request("GET", "/lists/bc9233b42a/interest-categories/35d7d5aa39/interests");
};
//Override the default Not Found Handler
$container['notFoundHandler'] = function ($container) {
    return function ($request, $response) use($container) {
        return $container['view']->render($response, '404.twig', []);
    };
};
/**
 * middleware
 */
// middleware to set the basePath global variable that we use in every template
$app->add(function ($request, $response, $next) {
    $uri = $request->getUri();
    $this->view->getEnvironment()->addGlobal('basePath', $uri->getBasePath());
    $request = $next($request, $response);
    return $response;
});
// Allow the trailing slash
$app->add(function ($request, $response, $next) {
    return $this->wynfordchace->allowTrailingSlash($request, $response, $next);
});
/**
 *  ROUTES
 */
// Home Route
$app->get('/', function ($request, $response, $args) {
    return $this->view->render($response, 'home.twig', ["pageInfo" => $this->menu->pageInfo("home"), "groups" => $this->mailChimpGroups->interests]);
})->setName('home');
// Primary internal page. Validated by the Menu structure
$app->get('/{page}', function ($request, $response, $args) {
Exemplo n.º 17
0
<?php

require_once __DIR__ . '/../vendor/autoload.php';
$app = new Slim\App(['settings' => ['determineRouteBeforeAppMiddleware' => true, 'middleware' => ['authentication' => ['filter_mode' => \DashTec\Middleware\AbstractFilterableMiddleware::EXCLUSION, 'route_names' => []], 'authorization' => ['filter_mode' => \DashTec\Middleware\AbstractFilterableMiddleware::INCLUSION, 'route_names' => []]]]]);
$app->add(new \DashTec\Middleware\AuthenticationMiddleware($app));
$app->get('/', function (\Slim\Http\Request $request, \Slim\Http\Response $response, $args) {
    return $response->write('aloha');
})->setName('index');
$app->run();
Exemplo n.º 18
0
    return $fb;
};
//Database Instance
$container['DB'] = function ($container) {
    //Create new database connection
    $db = new mysqli($GLOBALS['mysql']['host'], $GLOBALS['mysql']['username'], $GLOBALS['mysql']['password'], $GLOBALS['mysql']['database']);
    //Die if error
    if ($db->connect_errno > 0) {
        die('Unable to connect to data [' . $db->connect_error . ']');
    }
    //Return instance of database
    return $db;
};
//Setup the application
$app = new \Slim\App($container);
$app->add(function ($req, $res, $next) {
    /* @var $res \Slim\Http\Response */
    $res = $next($req, $res);
    $res = $res->withHeader('Content-type', 'application/json');
    return $res;
});
$app->get('/', function () {
    echo "Home Page";
});
//Helpers
require_once '../app/Helpers.php';
//Routes
require_once '../app/routes/Search.php';
require_once '../app/routes/Bucket.php';
require_once '../app/routes/Achievement.php';
$app->run();
Exemplo n.º 19
0
<?php

$APP_PATH = dirname(dirname(__FILE__));
$SERVER_PATH = dirname($APP_PATH);
$AliceSPA_PATH = $SERVER_PATH . '/AliceSPA';
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Message\ResponseInterface as Response;
use AliceSPA\Helper\Config as configHelper;
require $SERVER_PATH . '/vendor/autoload.php';
require $APP_PATH . '/Config/load.php';
$app = new \Slim\App(['settings' => $AliceSPAConfig['slimConfig']]);
require $AliceSPA_PATH . '/Exception/load.php';
require $AliceSPA_PATH . '/Service/load.php';
require $AliceSPA_PATH . '/Middleware/load.php';
require $AliceSPA_PATH . '/Helper/load.php';
//API
require $AliceSPA_PATH . '/API/load.php';
//--API
configHelper::setConfig($AliceSPAConfig);
configHelper::setErrors($AliceSPAErrors);
if (!empty(configHelper::getCoreConfig()['CORSOrigin'])) {
    $app->options('/{routes:.+}', function ($request, $response, $args) {
        return $response;
    });
    $app->add(function ($req, $res, $next) {
        $response = $next($req, $res);
        return $response->withHeader('Access-Control-Allow-Origin', configHelper::getCoreConfig()['CORSOrigin'])->withHeader('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type, Accept, Origin, Authorization' . ', AliceSPA-UserID, AliceSPA-WebToken, AliceSPA-SessionID')->withHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
    });
}
$app->run();
Exemplo n.º 20
0
<?php

require '../vendor/autoload.php';
$app = new \Slim\App(['debug' => true, 'whoops.editor' => 'sublime']);
//$app->add(new \SlimBooboo\Middleware());
$logger = new \Monolog\Logger('Test');
$logger->pushHandler(new \Monolog\Handler\StreamHandler("c:/xampp/php/logs/php_error_log"));
$app->add(new SlimWhoops\Middleware($app, $logger));
$app->get('/exception/', function ($req, $res, $arg) {
    throw new Exception("Error Processing Request", 1);
});
$app->get('/error/', function ($req, $res, $arg) {
    $a->B();
});
$app->run();
Exemplo n.º 21
0
        $stmt->execute();
        $resp = $stmt->fetch(PDO::FETCH_OBJ);
        $db = null;
        $response->getBody()->write(json_encode($resp, JSON_NUMERIC_CHECK));
    } catch (PDOException $e) {
        $response->getBody()->write(json_encode($e->getMessage()));
    }
});
$app->post('/suporte', function ($request, $response) {
    $data = $request->getParsedBody();
    $headers = "MIME-Version: 1.0\r\n";
    $headers .= "Content-type: text/html; charset=utf-8\r\n";
    $headers .= "From: {$data['nome']} <{$data['email']}>\r\n";
    mail('*****@*****.**', 'Suporte SGF', $data[mensagem], $headers);
});
$app->add(new \Slim\Middleware\HttpBasicAuthentication(['path' => '/app', 'authenticator' => function ($arguments) {
    $sql = "SELECT CASE WHEN usuario = '{$arguments['user']}' AND password = '******'password']}' THEN 1 ELSE 0 END acess FROM users";
    try {
        $db = getConnection();
        $stmt = $db->query($sql);
        $confirm = $stmt->fetch(PDO::FETCH_OBJ);
        if ($confirm->acess) {
            return true;
        } else {
            return false;
        }
    } catch (PDOException $e) {
        echo json_encode($e->getMessage());
    }
}]));
$app->run();
Exemplo n.º 22
0
require 'config.php';
use Illuminate\Database\Capsule\Manager as Capsule;
$capsule = new Capsule();
$capsule->addConnection(['driver' => 'mysql', 'host' => DB_HOST, 'port' => DB_PORT, 'database' => DB_NAME, 'username' => DB_USER, 'password' => DB_PASSWORD, 'charset' => 'utf8', 'collation' => 'utf8_unicode_ci']);
$capsule->bootEloquent();
$capsule->setAsGlobal();
$container = $app->getContainer();
$container['generateHash'] = function () {
    $factory = new RandomLib\Factory();
    $generator = $factory->getMediumStrengthGenerator();
    return $generator->generateString(8, $generator::CHAR_LOWER);
};
$container['cache'] = function () {
    return new \Slim\HttpCache\CacheProvider();
};
$app->add(new \Slim\HttpCache\Cache('public', 0));
$container['view'] = function ($c) {
    $view = new \Slim\Views\Twig('templates');
    $view->addExtension(new Slim\Views\TwigExtension($c['router'], $c['request']->getUri()));
    return $view;
};
$app->map(['GET', 'POST'], '/', function (\Slim\Http\Request $req, \Slim\Http\Response $res, $args) {
    if ($req->isPost()) {
        $board = new \Sprintboard\Model\Sprint();
        $board->name = $req->getParam('name');
        $board->hash = $this->generateHash;
        $board->save();
        return $res->withRedirect($this->router->pathFor('boardView', ['boardHash' => $board->hash]));
    }
    return $this->view->render($res, 'boardAdd.twig');
});
Exemplo n.º 23
0
<?php

require_once __DIR__ . '/../vendor/autoload.php';
$container = new \Slim\Container();
$container['config'] = (require_once __DIR__ . '/../app/settings.php');
require_once __DIR__ . '/../app/dependencies.php';
$app = new \Slim\App($container);
// Register middleware
$app->add(new \Slim\HttpCache\Cache('public', $container['config']['cache_lifetime']));
$app->get('/', function ($request, $response) {
    $domain = $this->environment['HTTP_HOST'];
    try {
        $this->sites->load();
        $target = $this->sites->lookup($domain);
    } catch (\Exception $e) {
        $target = (object) array('redirect' => $this->config['sites']['default_url']);
    }
    if (empty($target->status)) {
        $target->status = $this->config['sites']['default_status'];
    }
    $response = $response->withStatus($target->status)->withAddedHeader('Location', $target->redirect);
    return $response;
});
$app->put('/update', function ($request, $response) {
    /*
        if ('HTTPS' != $request->getUri()->getScheme()) {
       return $response->withStatus(400);
        }
    */
    $key = $this->config['shared_key'];
    $json = $request->getParsedBody();
Exemplo n.º 24
0
<?php

require '../vendor/autoload.php';
use Zeuxisoo\Whoops\Provider\Slim\WhoopsMiddleware;
$app = new \Slim\App(['debug' => true, 'whoops.editor' => 'sublime']);
$logger = (new \Monolog\Logger('TEST'))->pushHandler(new \Monolog\Handler\FingersCrossedHandler(new \Monolog\Handler\StreamHandler(__DIR__ . '/log'), \Monolog\Logger::WARNING));
$app->add(new \SlimBooboo\Middleware($app, [], $logger, true, function () {
    error_log("testing callable");
}, [E_NOTICE, E_DEPRECATED]));
$logger->notice('Starting the routing');
$app->get('/exception/', function ($req, $res, $arg) {
    throw new Exception("Error Processing Request", 1);
});
$app->get('/exception-booboo/', function ($req, $res, $arg) {
    throw new \Exception\BooBoo(new MyBooBoos\DatabaseError('The message for the client', 'The message for the logs', [1, 2, 3, 4]), (new \HTTP\Response())->withStatus(404)->withLanguage(\HTTP\Response\Language::DUTCH));
});
$app->get('/error/', function ($req, $res, $arg) {
    $a->B();
});
$app->run();
Exemplo n.º 25
0
<?php 
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Message\ResponseInterface as Response;
require 'vendor/autoload.php';
$app = new \Slim\App();
$app->add(function (Request $request, Response $response, callable $next) {
    $uri = $request->getUri();
    $path = $uri->getPath();
    if ($path != '/' && substr($path, -1) == '/') {
        // permanently redirect paths with a trailing slash
        // to their non-trailing counterpart
        $uri = $uri->withPath(substr($path, 0, -1));
        return $response->withRedirect((string) $uri, 301);
    }
    return $next($request, $response);
});
$app->get('/api/stryktipset', function (Request $request, Response $response) {
    $response = $response->withHeader('Content-type', 'application/json');
    require 'api/cStryktipsetApi.php';
    $response->getBody()->write(StryktipsetApi::getRow());
    return $response;
});
$app->get('/api/matches', function (Request $request, Response $response) {
    $response = $response->withHeader('Content-type', 'application/json');
    require 'api/cMatchesApi.php';
    $response->getBody()->write(MatchesApi::getMatches());
    return $response;
});
$app->get('/api/matches/{team}', function (Request $request, Response $response, $args) {
    $response = $response->withHeader('Content-type', 'application/json');
    require 'api/cMatchesApi.php';
Exemplo n.º 26
0
date_default_timezone_set(TIMEZONE);
use Illuminate\Database\Capsule\Manager as Capsule;
$capsule = new Capsule();
$capsule->addConnection(['driver' => 'mysql', 'host' => DB_HOST, 'port' => DB_PORT, 'database' => DB_NAME, 'username' => DB_USER, 'password' => DB_PASSWORD, 'charset' => 'utf8', 'collation' => 'utf8_unicode_ci']);
$capsule->bootEloquent();
$capsule->setAsGlobal();
$app = new Slim\App();
$configuration = ['settings' => ['displayErrorDetails' => true]];
$container = new \Slim\Container($configuration);
$app = new \Slim\App($container);
$filestore = new \Illuminate\Cache\FileStore(new \Illuminate\Filesystem\Filesystem(), 'cache/illuminate');
$container['cache'] = new \Illuminate\Cache\Repository($filestore);
$container['MediaService'] = new \Dullahan\Service\MediaService();
$container['ContentService'] = new \Dullahan\Service\ContentService();
$container['user'] = null;
$app->add(new RKA\Middleware\IpAddress());
/**
 * This middleware validates access token sent by client.
 *
 * Token must be a valid user token or app token. If the user token is valid, the middleware will set user object in
 * the container so that it's available in other parts of the application.
 */
$authMiddleware = function () {
    return function (\Slim\Http\Request $request, \Slim\Http\Response $response, $next) {
        $token = null;
        $tokenObject = null;
        if ($request->hasHeader('X-User-Token')) {
            $token = $request->getHeader('X-User-Token');
            $tokenObject = \Dullahan\Model\UserToken::where('value', $token)->first();
        }
        if ($request->hasHeader('X-App-Token')) {
Exemplo n.º 27
0
require __DIR__ . "/vendor/autoload.php";
use App\Todo;
use App\TodoTransformer;
use League\Fractal\Manager;
use League\Fractal\Resource\Item;
use League\Fractal\Resource\Collection;
use League\Fractal\Serializer\ArraySerializer;
use League\Fractal\Serializer\DataArraySerializer;
date_default_timezone_set("UTC");
$dotenv = new Dotenv\Dotenv(__DIR__);
$dotenv->load();
$app = new Slim\App(["settings" => ["displayErrorDetails" => true]]);
require __DIR__ . "/config/logger.php";
require __DIR__ . "/config/database.php";
$app->add(new \Tuupola\Middleware\Cors(["origin" => "*", "methods" => ["GET", "POST", "PATCH", "DELETE"], "headers.allow" => ["Content-Type", "Accept"], "credentials" => true, "cache" => 86400]));
$app->get("/", function ($request, $response, $arguments) {
    return $response->withStatus(301)->withHeader("Location", "/todos");
});
$app->get("/todos", function ($request, $response, $arguments) {
    $todos = $this->spot->mapper("App\\Todo")->all();
    $fractal = new Manager();
    $fractal->setSerializer(new ArraySerializer());
    $resource = new Collection($todos, new TodoTransformer());
    $data = $fractal->createData($resource)->toArray();
    /* Fractal collections are always namespaced. Apparently a feature and */
    /* not a bug. Thus we need to return $data["data"] for TodoMVC examples. */
    /* https://github.com/thephpleague/fractal/issues/110 */
    return $response->withStatus(200)->withHeader("Content-Type", "application/json")->write(json_encode($data["data"], JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT));
});
$app->post("/todos", function ($request, $response, $arguments) {
Exemplo n.º 28
0
        return $c['response']->withStatus(405)->withHeader('Allow', implode(', ', $methods))->withHeader('Content-type', 'application/json')->write(JsonHelper::fail('Metodo per la richiesta non valido. I metodi accettati sono: ' . implode(', ', $methods)));
    };
};
/**
 *
 */
$c['errorHandler'] = function ($c) {
    return function ($req, $res, $exception) use($c) {
        return $c['response']->withStatus(500)->withHeader('Content-Type', 'application/json')->write(JsonHelper::fail('La richiesta ha generato un errore inaspettato.'));
    };
};
/**
 *
 */
$app = new \Slim\App($c);
$app->add(new HandleCors());
$app->group('/api', function () use($app) {
    $app->group('/v1', function () use($app) {
        $app->add(new JsonResponse());
        /**
         *
         */
        $app->get('/catalog[/{table}]', function ($req, $res, $args) {
            $table = isset($args['table']) ? $args['table'] : null;
            $result = Store::catalog($table);
            if (!$result) {
                return $res->withStatus(404)->write(JsonHelper::fail('Tabella inesistente.'));
            }
            return $res->write(JsonHelper::success($result));
        });
        /**
Exemplo n.º 29
0
};
$container['db'] = function ($c) {
    $dsn = 'mysql:dbname=' . $_ENV['DB_NAME'] . ';host=' . $_ENV['DB_HOST'];
    return new \PDO($dsn, $_ENV['DB_USER'], $_ENV['DB_PASS']);
};
$container['flash'] = function () {
    return new \Slim\Flash\Messages();
};
// Make the session instance
$container['session'] = function () {
    $data = array();
    $sessionFactory = new \Aura\Session\SessionFactory();
    return $sessionFactory->newInstance($data);
};
$container['errorHandler'] = function ($c) {
    return function ($request, $response, $ex) use($c) {
        echo $c['view']->render($response, 'error/index.twig', ['message' => $ex->getMessage()]);
        return $c['response'];
    };
};
//----------------------
$app = new \Slim\App($container);
$app->add(new \Conftrack\Middleware\Auth($container));
// Load the controllers
$dir = new DirectoryIterator(APP_PATH . '/' . APP_NAMESPACE . '/Controller');
foreach ($dir as $fileinfo) {
    if (!$fileinfo->isDot()) {
        require_once $fileinfo->getPathname();
    }
}
$app->run();
Exemplo n.º 30
0
<?php

/**
 * Created by PhpStorm.
 * User: rg
 * Date: 10.12.15
 * Time: 14:00
 */
require 'vendor/autoload.php';
use Symfony\Component\Yaml\Yaml;
use Slim\Middleware\JwtAuthentication\RequestPathRule;
use Slim\Middleware\JwtAuthentication;
define('DIR', __DIR__);
$config = Yaml::parse(file_get_contents('config/app.yml'));
$app = new \Slim\App($config);
$app->add(new JwtAuthentication(['secret' => $config['app']['main']['secret'], 'rules' => [new RequestPathRule(["path" => "/", "passthrough" => ['/user/auth', '/user/register']])], 'callback' => function ($request, $response, $arguments) use($app) {
    $app->jwt = $arguments['decoded'];
}]));
require 'routes.php';
$app->run();