Example #1
1
 public function testGetDefaultConditions()
 {
     $property = new \ReflectionProperty('\\Slim\\Route', 'defaultConditions');
     $property->setAccessible(true);
     $property->setValue(array('id' => '\\d+'));
     $this->assertEquals(array('id' => '\\d+'), \Slim\Route::getDefaultConditions());
 }
/**
 * Insert/Update Group
 *
 * Controller for the Group module.
 *
 * @param \Slim\Route $route The route data array
 * @return void
 */
function insert_update_group(\Slim\Route $route)
{
    $app = \Slim\Slim::getInstance();
    $final_global_template_vars = $app->config('final_global_template_vars');
    require_once $final_global_template_vars["absolute_path_to_this_module"] . "/models/group.class.php";
    require_once $_SERVER["PATH_TO_VENDOR"] . "wixel/gump/gump.class.php";
    // URL parameters matched in the route.
    $params = $route->getParams();
    $group_id = isset($params["group_id"]) ? $params["group_id"] : false;
    $db_conn = new \PHPSkeleton\models\db($final_global_template_vars["db_connection"]);
    $db_resource = $db_conn->get_resource();
    $group = new \PHPSkeleton\Group($db_resource, $final_global_template_vars["session_key"]);
    $gump = new GUMP();
    $rules = array("name" => "required", "abbreviation" => "required|alpha_numeric", "state" => "alpha_numeric", "zip" => "numeric|exact_len,5", "group_parent" => "numeric");
    $validated = $gump->validate($app->request()->post(), $rules);
    $errors = array();
    if ($validated !== true) {
        $errors = \phpskeleton\models\utility::gump_parse_errors($validated);
    }
    if (!$errors) {
        $group->insert_update_group($app->request()->post(), $group_id);
        // If group_id is true, then the group was modified. Otherwise, it was created.
        if ($group_id) {
            $app->flash('message', 'The group has been successfully modified.');
        } else {
            $app->flash('message', 'New group has been successfully created.');
        }
        $app->redirect($final_global_template_vars["path_to_this_module"]);
    } else {
        $env = $app->environment();
        $env["default_validation_errors"] = $errors;
    }
}
 protected function shouldProcessRoute(Route $route)
 {
     $middlewareRouteFilterConfig = $this->settings['middleware'][$this->getConfigKey()];
     $filterMode = $this->getFilterModeFromFilterConfig($middlewareRouteFilterConfig);
     $routeNames = $middlewareRouteFilterConfig['route_names'];
     $result = in_array($route->getName(), $routeNames);
     return $filterMode === static::INCLUSION ? $result : !$result;
 }
Example #4
0
 private function loadMiddleWare(Route $route, $parameters)
 {
     $middleWare = $this->loadParameter('stack', $parameters);
     if (count($middleWare) > 0) {
         foreach ($middleWare as $key) {
             $route->add($this->container->get($key));
         }
     }
 }
 protected function processAtRoute(Route $route)
 {
     $configKeyName = 'middleware.' . $this->getConfigKey();
     $middlewareRouteFilterConfig = $this->app->config($configKeyName);
     $filterMode = $this->getFilterModeFromFilterConfig($middlewareRouteFilterConfig);
     $routeNames = $middlewareRouteFilterConfig['route_names'];
     $result = in_array($route->getName(), $routeNames);
     return $filterMode === static::INCLUSION ? $result : !$result;
 }
 /**
  * Api annotation
  * 
  * if you set the \@api annotation this text will be proccess like
  * api description that can be access with app->getApi(), you must set the version
  * of the api description.
  * 
  * if you set the @Route annotation the path will be proccesed like a path
  * definition for this controller and configured in the routing rutine. The 
  * \@RouteName annotation is optional and can be omited, if is omited the route
  * name will be configured in base of the route path.
  * 
  * @Route /new/example
  * @RouteName _new_example
  * @api example.gui
  * 
  * @param \Slim\Http\Request $request
  * @param \Slim\Http\Response $response
  * @param \Slim\Route $route
  */
 public function indexAction($request, $response, $route)
 {
     /**
      * You can use the next params
      * The current request, response and the route
      * 
      */
     return "Hello World !! " . $route->getName();
 }
Example #7
0
 /**
  * Add Routes
  *
  * @param array $routes            
  */
 public function addRoutes($routes)
 {
     foreach ($routes as $route => $path) {
         $method = "any";
         if (strpos($path, "@") !== false) {
             list($path, $method) = explode("@", $path);
         }
         $func = $this->processCallback($path);
         $r = new Route($route, $func);
         $r->setHttpMethods(strtoupper($method));
         array_push($this->routes, $r);
     }
 }
Example #8
0
 /**
  * Constructor.
  *
  * @param array $options The SameAs Lite Store for which we shall
  * provide RESTful interfaces.
  */
 public function __construct(array $options = array())
 {
     // fake $_SERVER parameters if required (eg command line invocation)
     \SameAsLite\Helper::initialiseServerParameters();
     // set the default format of acceptable parameters
     // see http://docs.slimframework.com/routing/conditions/#application-wide-route-conditions
     \Slim\Route::setDefaultConditions(array('store' => '[a-zA-Z0-9_\\-\\.]+'));
     // initialise and configure Slim, using Twig template engine
     $mode = isset($options['mode']) ? $options['mode'] : 'production';
     $this->app = new \Slim\Slim(array('mode' => $mode, 'debug' => false, 'view' => new \Slim\Views\Twig()));
     // configure Twig
     $this->app->view()->setTemplatesDirectory('assets/twig/');
     $this->app->view()->parserOptions['autoescape'] = false;
     $this->app->view()->set('path', $this->app->request()->getRootUri());
     // register 404 and custom error handlers
     $this->app->notFound(array(&$this, 'outputError404'));
     $this->app->error(array(&$this, 'outputException'));
     // '\SameAsLite\Exception\Exception::outputException'
     set_exception_handler(array(&$this, 'outputException'));
     // '\SameAsLite\Exception\Exception::outputException'
     // Hook to set the api path
     $this->app->hook('slim.before.dispatch', function () {
         // fix api pages such that if viewing a particular store
         // then the store name is automatically injected for you
         $params = $this->app->router()->getCurrentRoute()->getParams();
         if (isset($params['store'])) {
             $apiPath = "datasets/{$params['store']}/api";
         } else {
             $apiPath = 'api';
         }
         $this->app->view()->set('apiPath', $apiPath);
     });
     // save the options
     $this->appOptions = $options;
     // apply options to template
     foreach ($options as $k => $v) {
         $this->app->view->set($k, $v);
     }
 }
 /**
  * Get the route information for a given route.
  *
  * @param  Route $route
  * @return array
  */
 protected function getRouteInformation(Route $route)
 {
     $result = [];
     $result['uri'] = $route->getMethods()[0] . ' ' . $route->getPattern();
     $result['name'] = $route->getName() ?: '';
     $result['group'] = '';
     foreach ($route->getGroups() as $group) {
         $result['group'] .= $group->getPattern();
     }
     $callable = $route->getCallable();
     $result['middleware'] = [];
     foreach ($route->getMiddleware() as $middleware) {
         $result['middleware'][] = Closure::bind(function () {
             return get_class($this->callable);
         }, $middleware, DeferredCallable::class)->__invoke();
     }
     if (is_array($callable)) {
         $result['callable'] = get_class($callable[0]) . ':' . $callable[1];
         $reflector = new ReflectionMethod($callable[0], $callable[1]);
     } elseif ($callable instanceof Closure) {
         $result['callable'] = $this->formatVar($callable);
         $reflector = new ReflectionFunction($callable);
     } elseif (is_object($callable)) {
         $result['callable'] = get_class($callable);
         $reflector = new ReflectionMethod($callable, '__invoke');
     } else {
         $result['callable'] = $callable;
         $callable = explode(':', $callable);
         if (isset($callable[1])) {
             $reflector = new ReflectionMethod($callable[0], $callable[1]);
         } else {
             $reflector = new ReflectionMethod($callable, '__invoke');
         }
     }
     $result['file'] = $reflector->getFileName() . ':' . $reflector->getStartLine() . '-' . $reflector->getEndLine();
     return $result;
 }
Example #10
0
<?php

if (!isset($rpVersion)) {
    die;
}
// globally set some Twig variables
$app->view()->setData(array('docroot' => $app->request->getRootUri() . '/', 'version' => $rpVersion));
// All room ID's must be alphanumeric and N characters
\Slim\Route::setDefaultConditions(array('id' => '[' . preg_quote($rpIDChars) . ']{' . $rpIDLength . '}'));
// numeric routes use this regex
$numericRouteCondition = '[1-9][0-9]{0,}';
// Maintenance Mode Middleware
$downCheck = function () use($app) {
    global $rpDown;
    if (isset($rpDown)) {
        $app->response->setStatus(503);
        $app->view()->setData(array('info' => $rpDown));
        $app->render('down.html');
        $app->stop();
    }
};
$downCheckAjax = function () use($app) {
    global $rpDown;
    if (isset($rpDown)) {
        $app->halt(503);
    }
};
// Error pages
$app->notFound(function () use($app) {
    $app->view()->setData(array('uri' => $app->request->getResourceUri()));
    $app->render('404.html');
 /**
  * Ensure that if `outputBuffering` property is set to `false` correct response
  * body is returned by __invoke().
  */
 public function testInvokeWhenDisablingOutputBuffer()
 {
     ob_start();
     $callable = function ($req, $res, $args) {
         echo 'foo';
         return $res->write('bar');
     };
     $route = new Route(['GET'], '/', $callable);
     $route->setOutputBuffering(false);
     $env = Environment::mock();
     $uri = Uri::createFromString('https://example.com:80');
     $headers = new Headers();
     $cookies = [];
     $serverParams = $env->all();
     $body = new Body(fopen('php://temp', 'r+'));
     $request = new Request('GET', $uri, $headers, $cookies, $serverParams, $body);
     $response = new Response();
     $response = $route->__invoke($request, $response);
     $this->assertEquals('bar', (string) $response->getBody());
     $output = ob_get_clean();
     $this->assertEquals('foo', $output);
 }
Example #12
0
 /**
  * Add a route object to the router
  * @param  \Slim\Route     $route      The Slim Route
  */
 public function map(\Slim\Route $route)
 {
     list($groupPattern, $groupMiddleware) = $this->processGroups();
     $route->setPattern($groupPattern . $route->getPattern());
     $this->routes[] = $route;
     foreach ($groupMiddleware as $middleware) {
         $route->setMiddleware($middleware);
     }
 }
Example #13
0
function authenticate(\Slim\Route $route)
{
    $app = \Slim\Slim::getInstance();
    $query = new QueryHandler();
    $auth = new HashGenerator();
    // Getting request headers
    $headers = apache_request_headers();
    $requestURI = $_SERVER['REQUEST_URI'];
    $requestMethod = $app->request->getMethod();
    $params = $route->getParams();
    try {
        $userId = intval($params['userId']);
        if (!$userId > 0) {
            $userId = DEFAULT_USER;
        }
    } catch (Exception $e) {
        $userId = DEFAULT_USER;
    }
    // TEST CODE ****************************
    $testParams = implode(',', getRequestParams());
    echo "<h3>{$testParams}</h3>";
    // END TEST CODE ************************
    // Get Handshake KEY
    if (!isset($headers['Authorization'])) {
        // api key is missing in header
        exitApp(BAD_REQUEST, "Authorization key is misssing");
    }
    // Get User Access Key
    if (!isset($headers['AccessKey']) && $userId !== DEFAULT_USER) {
        // api key is missing in header
        exitApp(BAD_REQUEST, "Access key is misssing");
    }
    $auth_key = $headers['Authorization'];
    @($accessKey = $headers['AccessKey']);
    $stringParams = implode(',', getRequestParams());
    // AUTHORIZE ADMIN OPERATION
    $adminData = "admin" . $requestURI . "#" . $stringParams;
    $adminHash = $auth->getAuthHash($adminData);
    $userData = $userId . $requestURI . "#" . $stringParams;
    // 		echo $userData;
    $userHash = $auth->getAuthHash($userData);
    // route the authorization for USER or ADMIN
    switch ($auth_key) {
        case $adminHash:
            // check if admin is valid
            $admin = $query->getAdmin($accessKey);
            if (empty($admin)) {
                exitApp(UNAUTHORIZED, "Admin not found!");
            }
            //Check admin access level
            if ($admin[ADMIN_FIELDS::ACCESS_LEVEL == "read"] && $requestMethod != "GET") {
                exitApp(UNAUTHORIZED, "Limited admin access !");
            }
            // admin is verified
            break;
        case $userHash:
            //non-user operation
            if ($userId == DEFAULT_USER) {
                break;
            }
            // UserOperatoin: check if user is valid
            $user_array = $query->getUser(array(USER_FIELDS::ACCESS_KEY => $accessKey));
            if (empty($user_array)) {
                exitApp(UNAUTHORIZED, "Invalid access key!");
            }
            if ($user_array[USER_FIELDS::IS_ACTIVE] == false) {
                // if requesting login
                if (strpos($requestURI, 'login') !== false) {
                    $message = "Please activate your account";
                }
                // for other operation
                $message = "Your account has been deactivated.";
                exitApp(UNAUTHORIZED, $message);
            }
            if ($user_array[USER_FIELDS::USER_ID] != $userId) {
                exitApp(UNAUTHORIZED, "You are not authorized to access others data");
            }
            break;
        default:
            exitApp(UNAUTHORIZED, "Invalid authorization key !");
    }
}
 /**
  * Connects a controller with multiples routes.
  *
  * Usage :
  * connectRoutes(
  * 		'MyController',
  * 		array(
  *			'/foo' => array(
  * 				'action' => 'myAction',
  * 				'param' => '',
  * 				'param' => '',
  * 				...
  * 			)
  * 		)
  * 		[, middleware, middleware, ...]
  * );
  *
  * @param string 	$controller Controller name, ex. : 'MyController'
  * @param array 	$routes 	List of routes and their parameters
  * @param callable 				Globals middlewares, called for each route
  */
 public function connectRoutes($controller, array $routes)
 {
     ## get global middlewares if exists
     if (func_num_args() > 2) {
         $globalMiddlewares = array_slice(func_get_args(), 2);
     }
     ## parse routes
     foreach ($routes as $pattern => $params) {
         if (!isset($params['action'])) {
             throw new \Exception('route action parameter is required');
         }
         ## creates route
         $methodName = $params['action'];
         $routeCallable = function () use($controller, $methodName) {
             $instance = $this->register($controller);
             return call_user_func_array(array($instance, $methodName), func_get_args());
         };
         $route = new Route($pattern, $routeCallable);
         ## binds HTTP methods
         $params['method'] = isset($params['method']) && is_string($params['method']) ? $params['method'] : 'GET';
         $methods = explode('|', $params['method']);
         foreach ($methods as $m) {
             $route->via($m);
         }
         ## binds route name
         if (isset($params['name']) && is_string($params['name'])) {
             $route->name($params['name']);
         }
         ## binds route conditions
         if (isset($params['conditions']) && is_array($params['conditions'])) {
             $route->conditions($params['conditions']);
         }
         ## binds middlewares
         $middlewares = isset($globalMiddlewares) ? $globalMiddlewares : array();
         $middlewares = isset($params['middlewares']) && is_array($params['middlewares']) ? array_merge($middlewares, $params['middlewares']) : $middlewares;
         if (!empty($middlewares)) {
             $this->bindMiddlewares($route, $middlewares);
         }
         ## map to router
         $this->_slim->router()->map($route);
     }
 }
Example #15
0
require '../vendor/autoload.php';
use Pkj\Raspberry\PiFace\PiFaceDigital;
if (!class_exists('\\Spi')) {
    die("Spi extension must be installed (https://github.com/frak/php_spi)");
}
$app = new \Slim\Slim(array('debug' => false));
// Exception handler (make sure debug is false above)
$app->error(function (\Exception $e) use($app) {
    print json_encode(array('status' => '500', 'exception' => array('code' => $e->getCode(), 'message' => $e->getMessage())));
});
$app->notFound(function () use($app) {
    print json_encode(array('status' => '404', 'message' => 'Route not found'));
});
$pi = PiFaceDigital::create();
// Defining min/max values
\Slim\Route::setDefaultConditions(array('input' => '[0-' . (count($pi->getInputPins()) - 1) . ']', 'led' => '[0-' . (count($pi->getLeds()) - 1) . ']', 'output' => '[0-' . (count($pi->getOutputPins()) - 1) . ']', 'relay' => '[0-' . (count($pi->getRelays()) - 1) . ']', 'switch' => '[0-' . (count($pi->getSwitches()) - 1) . ']', 'value' => '[0-1]'));
// Begin read only devices
// Input
$app->get('/input/', function () use($app, $pi) {
    responseSuccess(outputAll($pi->getInputPins()));
});
$app->get('/input/:input', function ($input) use($app, $pi) {
    responseSuccess($pi->getInputPins()[$input]->getValue());
});
// Switch
$app->get('/switch/', function () use($app, $pi) {
    responseSuccess(outputAll($pi->getSwitches()));
});
$app->get('/switch/:switch', function ($switch) use($app, $pi) {
    responseSuccess($pi->getSwitches()[$switch]->getValue());
});
 /**
  * Add route
  *
  * @param  string[] $methods Array of HTTP methods
  * @param  string   $pattern The route pattern
  * @param  callable $handler The route callable
  *
  * @return RouteInterface
  *
  * @throws InvalidArgumentException if the route pattern isn't a string
  */
 public function map($methods, $pattern, $handler)
 {
     if (!is_string($pattern)) {
         throw new InvalidArgumentException('Route pattern must be a string');
     }
     // Prepend parent group pattern(s)
     if ($this->routeGroups) {
         $pattern = $this->processGroups() . $pattern;
     }
     // According to RFC methods are defined in uppercase (See RFC 7231)
     $methods = array_map("strtoupper", $methods);
     // Add route
     $route = new Route($methods, $pattern, $handler, $this->routeGroups, $this->routeCounter);
     $this->routes[$route->getIdentifier()] = $route;
     $this->routeCounter++;
     return $route;
 }
Example #17
0
 /**
  * Add application-wide route conditions.
  *
  * @see \Slim\Route::setDefaultConditions
  * @return void
  */
 public static function conditions($args)
 {
     return \Slim\Route::setDefaultConditions($args);
 }
Example #18
0
 /**
  * Test route default conditions
  *
  * Pre-conditions:
  * Route class has default conditions;
  *
  * Post-conditions:
  * Case A: Route instance has default conditions;
  * Case B: Route instance has newly merged conditions;
  */
 public function testRouteDefaultConditions()
 {
     \Slim\Route::setDefaultConditions(array('id' => '\\d+'));
     $r = new \Slim\Route('/foo', function () {
     });
     //Case A
     $this->assertEquals(\Slim\Route::getDefaultConditions(), $r->getConditions());
     //Case B
     $r->conditions(array('name' => '[a-z]{2,5}'));
     $c = $r->getConditions();
     $this->assertArrayHasKey('id', $c);
     $this->assertArrayHasKey('name', $c);
 }
 /**
  * Create new route
  *
  * @param string[]     				$methods The route HTTP methods
  * @param string       				$pattern The route pattern
  * @param callable     				$callable The route callable
  * @param int          				$identifier The route identifier
  * @param RouteGroup[] 				$groups The parent route groups
  * @param \Zend\Permissions\Acl\Acl 	$acl
  */
 public function __construct($methods, $pattern, $callable, $groups, $identifier, &$acl = null)
 {
     $this->acl =& $acl;
     parent::__construct($methods, $pattern, $callable, $groups, $identifier);
 }
 * "Cross-origion resource sharing" kontrolüne izin verilmesi için eklenmiştir
 * @author Mustafa Zeynel Dağlı
 * @since 2.10.2015
 */
$res = $app->response();
$res->header('Access-Control-Allow-Origin', '*');
$res->header("Access-Control-Allow-Methods: PUT, GET, POST, DELETE, OPTIONS");
//$app->add(new \Slim\Middleware\MiddlewareTest());
$app->add(new \Slim\Middleware\MiddlewareHMAC());
$app->add(new \Slim\Middleware\MiddlewareSecurity());
$app->add(new \Slim\Middleware\MiddlewareBLLManager());
$app->add(new \Slim\Middleware\MiddlewareDalManager());
$app->add(new \Slim\Middleware\MiddlewareServiceManager());
$app->add(new \Slim\Middleware\MiddlewareMQManager());
$pdo = new PDO('pgsql:dbname=ecoman_01_10;host=88.249.18.205;user=postgres;password=1q2w3e4r');
\Slim\Route::setDefaultConditions(array('firstName' => '[a-zA-Z]{3,}', 'page' => '[0-9]{1,}'));
/**
 *  * Okan CIRAN
 * @since 07-01-2016
 */
$app->get("/pkFillComboBoxMainRoles_sysAclRoles/", function () use($app) {
    $BLL = $app->getBLLManager()->get('sysAclRolesBLL');
    //print_r('--****************get parent--' );
    $resCombobox = $BLL->fillComboBoxMainRoles();
    //print_r($resDataMenu);
    $flows = array();
    foreach ($resCombobox as $flow) {
        $flows[] = array("id" => $flow["id"], "text" => $flow["name"], "state" => 'open', "checked" => false, "attributes" => array("notroot" => true, "active" => $flow["active"], "deleted" => $flow["deleted"]));
    }
    //   print_r($flows);
    $app->response()->header("Content-Type", "application/json");
Example #21
0
 /**
  * Dispatch route
  *
  * This method invokes the route object's callable. If middleware is
  * registered for the route, each callable middleware is invoked in
  * the order specified.
  *
  * @param  \Slim\Route                  $route  The route object
  * @return bool                         Was route callable invoked successfully?
  */
 public function dispatch(\Slim\Route $route)
 {
     $this->currentRoute = $route;
     //Invoke middleware
     foreach ($route->getMiddleware() as $mw) {
         call_user_func_array($mw, array($route));
     }
     //Invoke callable
     call_user_func_array($route->getCallable(), array_values($route->getParams()));
     return true;
 }
Example #22
0
 /**
  * Add route
  *
  * @param  string[] $methods Array of HTTP methods
  * @param  string   $pattern The route pattern
  * @param  callable $handler The route callable
  *
  * @return RouteInterface
  *
  * @throws InvalidArgumentException if the route pattern isn't a string
  */
 public function map($methods, $pattern, $handler)
 {
     if (!is_string($pattern)) {
         throw new InvalidArgumentException('Route pattern must be a string');
     }
     // pattern must start with a / if not empty
     if ($pattern) {
         $pattern = '/' . ltrim($pattern, '/');
     }
     // Prepend parent group pattern(s)
     if ($this->routeGroups) {
         $pattern = $this->processGroups() . $pattern;
     }
     // Complete pattern must start with a /
     $pattern = '/' . ltrim($pattern, '/');
     // Add route
     $route = new Route($methods, $pattern, $handler, $this->routeGroups, $this->routeCounter);
     $this->routes[$route->getIdentifier()] = $route;
     $this->routeCounter++;
     return $route;
 }
 /**
  * Check if the given url should be skipped or not
  *
  * @param string $url The url to test
  * @return boolean True if it is register as skipped, false in other cases
  */
 public function isSkip($url)
 {
     // We need slim route for testing purpose
     $route = new \Slim\Route('', function () {
     });
     foreach ($this->skip as $skipped) {
         // We set the path we want to try
         $route->setPattern($skipped);
         if ($route->matches($url)) {
             return true;
         }
     }
     return false;
 }
Example #24
0
<?php

require_once dirname(__FILE__) . "/common.inc.php";
define("GALLERY_MAX_PER_PAGE", 18);
use Pagerfanta\Pagerfanta;
use Pagerfanta\Adapter\ArrayAdapter;
use Pagerfanta\View\TwitterBootstrap3View;
\Slim\Route::setDefaultConditions(array('lang' => 'en|ja'));
$twigView = new \Slim\Extras\Views\Twig();
$app = new \Slim\Slim(array('debug' => SLIM_DEBUG, 'view' => $twigView, 'templates.path' => dirname(__FILE__) . "/templates"));
$app->hook('slim.before', function () use($app) {
    $app->view()->appendData(array('base_url' => BASE_URL));
});
$app->get("/", function () use($app) {
    index($app, "en");
});
$app->get("/:lang/?", function ($lang) use($app) {
    index($app, $lang);
});
function index($app, $lang)
{
    if (!file_exists($app->view()->getTemplatesDirectory() . "/" . $lang . "/index.html")) {
        $app->notFound();
        return;
    }
    $api_type = $app->request()->params("api_type");
    if (isset($GLOBALS["api_type_list"][$api_type])) {
        $cs_id = $app->request()->params("cs_id");
        if (!ctype_digit($cs_id)) {
            $cs_id = "";
        }
Example #25
0
/**
 * LICENSE: This source code is subject to the license that is available
 * in the LICENSE file distributed along with this package.
 *
 * @package    Penelope
 * @author     Matthew Caruana Galizia <*****@*****.**>
 * @copyright  Karwana Ltd
 * @since      File available since Release 1.0.0
 */
namespace Karwana\Penelope;

const VERSION = '1.0.0';
use Closure;
use Slim;
use Everyman\Neo4j;
Slim\Route::setDefaultConditions(array('node_id' => '\\d+', 'edge_id' => '\\d+'));
class Penelope
{
    use OptionContainer;
    private $schema, $app, $client;
    protected static $defaults = array('path.format.uploads' => '/uploads/:file_name', 'path.format.resources' => '/resources/:resource_path+', 'path.format.search' => '/search');
    public function __construct(Neo4j\Client $client, Slim\Slim $app, Theme $theme = null, array $options = null)
    {
        $this->setOptions($options);
        $this->app = $app;
        $this->client = $client;
        $this->schema = new Schema($client);
        if ($theme) {
            $this->setTheme($theme);
        }
        if ($this->hasOption('upload.directory')) {
Example #26
0
<?php

/************************************************
Filtros globales para parametros

Proyecto: API Rest Full - Codeando.org
Author: Paulo Andrade
Email: source.compug@mail.com
Web: http://www.pauloandrade1.com
************************************************/
// Creamos las condiciones para los parametros
\Slim\Route::setDefaultConditions(array('id' => '[0-9]{0,3}'));
Example #27
0
    $v->setData('lang', $lang);
    $v->setData('negate', $ui['negate']);
    $v->setData('contrast', $ui['contrast']);
    $v->setData('brightness', $ui['brightness']);
    $v->setData('print', $ui['print']);
    $v->setData('comment', $conf->getComment());
    $fmts = $conf->getFormats();
    $v->setData('thumb_format', $fmts['thumb']);
    $remote_infos = $conf->getRemoteInfos();
    if ($remote_infos !== false) {
        $v->setData('remote_method', $remote_infos['method']);
        $v->setData('remote_uri', $remote_infos['uri']);
    }
});
//set default conditions
Route::setDefaultConditions(array('image' => '.+\\.[a-zA-Z]{3,4}', 'series' => '.+', 'format' => 'full|' . implode('|', array_keys($conf->getFormats()))));
//404 handler
$app->notFound(function () use($app) {
    $app->render('404.html.twig');
});
//custom error handler
$app->error(function (\Exception $e) use($app, $conf, $app_base_url) {
    $resuUri = $app->request()->getResourceUri();
    $etype = get_class($e);
    Analog::error('exception \'' . $etype . '\' with message \'' . $e->getMessage() . '\' in ' . $e->getFile() . ':' . $e->getLine() . "\nStack trace:\n" . $e->getTraceAsString());
    if ((substr($resuUri, 0, 10) === '/ajax/img/' || substr($resuUri, 0, 21) === '/ajax/representative/') && APP_DEBUG !== true) {
        $format = 'default';
        preg_match('/.*\\/format\\/(.*)/', $resuUri, $matches);
        if (isset($matches[1])) {
            $format = $matches[1];
        }
Example #28
0
// https://github.com/zynga/saigon
// Author: Matt West (https://github.com/mhwest13)
// License: BSD 2-Clause
//
/*
 * Saigon API - Index
 */
// Lets load up the composer autoloader
require_once dirname(dirname(__FILE__)) . '/conf/saigon.inc.php';
require_once BASE_PATH . '/vendor/autoload.php';
// Lets load up the saigon autoloader
require_once BASE_PATH . '/lib/classLoader.class.php';
Saigon_ClassLoader::register();
// Lets start up Slim...
$app = new \Slim\Slim();
\Slim\Route::setDefaultConditions(array('deployment' => '[a-zA-Z0-9_-]{1,}', 'staged' => '[1]', 'merged' => '[1]'));
// Internal functions
function check_auth($app, $deployment)
{
    $amodule = AUTH_MODULE;
    $authmodule = new $amodule();
    $return = $authmodule->checkAuth($deployment);
    if ($return === false) {
        $apiResponse = new APIViewData(1, $deployment, "Invalid Login or Invalid Credentials Supplied");
        $app->halt(401, $apiResponse->returnJson());
    }
    return true;
}
function check_revision_status($deployment)
{
    $currRev = RevDeploy::getDeploymentRev($deployment);
Example #29
0
 /**
  * Dispatch route
  *
  * This method invokes the route object's callable. If middleware is
  * registered for the route, each callable middleware is invoked in
  * the order specified.
  *
  * This method is smart about trailing slashes on the route pattern.
  * If the route's pattern is defined with a trailing slash, and if the
  * current request URI does not have a trailing slash but otherwise
  * matches the route's pattern, a Slim_Exception_RequestSlash
  * will be thrown triggering an HTTP 301 Permanent Redirect to the same
  * URI _with_ a trailing slash. This Exception is caught in the
  * `Slim::call` loop. If the route's pattern is defined without a
  * trailing slash, and if the current request URI does have a trailing
  * slash, the route will not be matched and a 404 Not Found
  * response will be sent if no subsequent matching routes are found.
  *
  * @param  \Slim\Route                  $route  The route object
  * @return bool                         Was route callable invoked successfully?
  * @throws \Slim\Exception\RequestSlash
  */
 public function dispatch(\Slim\Route $route)
 {
     if (substr($route->getPattern(), -1) === '/' && substr($this->resourceUri, -1) !== '/') {
         throw new Exception\RequestSlash();
     }
     //Invoke middleware
     foreach ($route->getMiddleware() as $mw) {
         if (is_callable($mw)) {
             call_user_func_array($mw, array($route));
         }
     }
     //Invoke callable
     if (is_callable($route->getCallable())) {
         call_user_func_array($route->getCallable(), array_values($route->getParams()));
         return true;
     }
     return false;
 }
function not_same_user(\Slim\Route $route)
{
    $params = $route->getParams();
    if (intval($params["userid"]) === intval($_SESSION['user']['meetup_id'])) {
        $data = array('status' => 'error', 'message' => 'You are not' . $params["userid"]);
        die(json_encode($data));
    }
}