Example #1
9
 protected function execute()
 {
     $pathinfo = pathinfo($this->server->getParam('SCRIPT_NAME'));
     $basePath = $pathinfo['dirname'];
     $router = new \AltoRouter();
     $router->setBasePath($basePath);
     $routes = $this->metadata->getMetadata('routes');
     foreach ($routes as $route) {
         $router->map($route['method'], $route['rule'], $route['target']);
     }
     $match = $router->match();
     if (!empty($match)) {
         $this->parameters = array_merge($match['target'], $match['params']);
     }
 }
Example #2
1
 /**
  * Handles a Request to convert it to a Response.
  *
  * When $catch is true, the implementation must catch all exceptions
  * and do its best to convert them to a Response instance.
  *
  * @param Request $request A Request instance
  * @param int     $type    The type of the request
  *                         (one of HttpKernelInterface::MASTER_REQUEST or HttpKernelInterface::SUB_REQUEST)
  * @param bool    $catch   Whether to catch exceptions or not
  *
  * @return Response A Response instance
  *
  * @throws \Exception When an Exception occurs during processing
  */
 public function handle(Request $request, $type = self::MASTER_REQUEST, $catch = true)
 {
     try {
         $match = $this->routeMatch;
         if (!$match) {
             $match = $this->router->match($request->getPathInfo());
         }
         if ($match) {
             list($module, $controller, $action) = $this->processRoute($match);
             $request->attributes->add(['_module' => $module, '_controller' => $controller, '_action' => $action]);
             $response = $this->dispatcher->dispatch($match['target'], $match['params']);
         } else {
             $response = $this->dispatcher->dispatch('Home#error', ['message' => 'Halaman tidak ditemukan: ' . $request->getPathInfo()]);
             $response->setStatusCode(Response::HTTP_NOT_FOUND);
         }
     } catch (HttpException $e) {
         if (!$catch) {
             throw $e;
         }
         $response = $this->dispatcher->dispatch('Home#error', ['message' => '[' . $e->getCode() . '] ' . $e->getMessage()]);
         $response->setStatusCode($e->getStatusCode());
     } catch (Exception $e) {
         if (!$catch) {
             throw $e;
         }
         $response = $this->dispatcher->dispatch('Home#error', ['message' => '[' . $e->getCode() . '] ' . $e->getMessage()]);
         $response->setStatusCode(Response::HTTP_INTERNAL_SERVER_ERROR);
     }
     //$response->setMaxAge(300);
     return $response;
 }
Example #3
0
 public function handle(Request $request, $type = self::MASTER_REQUEST, $catch = true)
 {
     $match = $this->router->match($request->getPathInfo());
     $route = substr($request->getPathInfo(), strlen(rtrim($this->config['baseDir'], '/')));
     if ($match) {
         $tokenValid = false;
         $jwtCookie = $this->config['jwt']['cookieName'];
         $jwtKey = $this->config['jwt']['key'];
         // check token from cookie
         if ($request->cookies->has($jwtCookie)) {
             $jwt = $request->cookies->get($jwtCookie);
             try {
                 $decoded = JWT::decode($jwt, $jwtKey, ['HS256']);
                 if ($decoded->e > time()) {
                     $tokenValid = true;
                     $this->auth->init($decoded->uid);
                 }
             } catch (\Exception $e) {
                 $tokenValid = false;
                 if (!$catch) {
                     throw $e;
                 }
                 $response = $this->dispatcher->dispatch('Home#error', ['message' => '[' . $e->getCode() . '] ' . $e->getMessage() . '<pre>' . $e->getTraceAsString() . '</pre>']);
                 $response->setStatusCode(Response::HTTP_INTERNAL_SERVER_ERROR);
                 return $response;
             }
         }
         $allowed = false;
         $isPublic = false;
         foreach ($this->config['publicArea'] as $publicRoute) {
             if (preg_match('/^' . addcslashes($publicRoute, '/') . '/', $route)) {
                 $isPublic = true;
                 break;
             }
         }
         if ($match['name'] == 'home') {
             $isPublic = true;
         }
         if ($isPublic) {
             if ($route == '/login' && $tokenValid) {
                 return new RedirectResponse($this->router->generate('dashboard'));
             }
             $allowed = true;
         } else {
             $allowed = $tokenValid;
         }
         if ($allowed) {
             $this->app->setRouteMatch($match);
             return $this->app->handle($request, $type, $catch);
         } else {
             $this->flash->warning('Sesi Anda telah habis atau Anda tidak berhak mengakses halaman ini, silakan login terlebih dahulu!');
             $response = $this->dispatcher->dispatch('User#login', []);
             $response->setStatusCode(Response::HTTP_UNAUTHORIZED);
             return $response;
         }
     }
     $response = $this->dispatcher->dispatch('Home#error', ['message' => 'Halaman tidak ditemukan: ' . $route]);
     $response->setStatusCode(Response::HTTP_NOT_FOUND);
     return $response;
 }
Example #4
0
 /**
  * @param Request $request
  * @return mixed|JsonResponse|Response
  */
 protected function handle(Request $request = null)
 {
     try {
         $this->response = $this->get('Response');
         // dispatch app-start events
         $this->eventDispatcher->emit('app-start');
         $matchedRoutes = $this->router->match();
         if ($matchedRoutes === false) {
             // dispatch app-failed-dispatch events
             $this->eventDispatcher->emit('app-failed-dispatch', 404);
         } else {
             // dispatch app-before-dispatch events
             $this->eventDispatcher->emit('app-before-dispatch');
             list($controller, $action) = explode(":", $matchedRoutes['target']);
             $controller = $this->container->get('\\App\\Http\\' . $controller);
             $methodResolver = new MethodResolver($controller, $action, $matchedRoutes['params']);
             $methodArguments = $methodResolver->getMethodArguments();
             $response = call_user_func_array(array($controller, $action), $methodArguments);
             $this->processResponseType($response);
             // dispatch app-before-dispatch events
             $this->eventDispatcher->emit('app-after-dispatch');
         }
         $this->response->send();
     } catch (\Exception $e) {
         $this->eventDispatcher->emit('app-error', 500, $e);
     }
     // dispatch app-start events
     $this->eventDispatcher->emit('app-end');
 }
Example #5
0
 public static function mapAllCTL()
 {
     $router = new \AltoRouter();
     $basePath = AppConfig::get("route.base_path");
     if (!is_null($basePath) && trim($basePath) != "") {
         $router->setBasePath($basePath);
     }
     $ctls = self::readCTL();
     foreach ($ctls as $ctl) {
         $router->map(implode('|', $ctl['methods']), $ctl['uri'], array('c' => $ctl['controller'], 'a' => $ctl['action']));
     }
     return $router;
 }
Example #6
0
 public function testMatchWithCustomNamedRegex()
 {
     $this->router->addMatchTypes(array('cId' => '[a-zA-Z]{2}[0-9](?:_[0-9]++)?'));
     $this->router->map('GET', '/bar/[cId:customId]', 'bar_action', 'bar_route');
     $this->assertEquals(array('target' => 'bar_action', 'params' => array('customId' => 'AB1'), 'name' => 'bar_route'), $this->router->match('/bar/AB1', 'GET'));
     $this->assertEquals(array('target' => 'bar_action', 'params' => array('customId' => 'AB1_0123456789'), 'name' => 'bar_route'), $this->router->match('/bar/AB1_0123456789', 'GET'));
     $this->assertFalse($this->router->match('/some-other-thing', 'GET'));
 }
Example #7
0
 /**
  * Performs a dispatching mechanism.
  *
  * @return void
  */
 public function dispatch()
 {
     $match = $this->altoRouter->match();
     if (!$match) {
         container("ViewContract")->render("errors.404")->withCode(404);
         // TODO: be sure that errors.404 exists - check it! Allow user add custom 404 file.
         exit;
     }
     $this->processMatch($match);
 }
Example #8
0
 public function testMatchWithCustomNamedUnicodeRegex()
 {
     $pattern = '[^';
     // Arabic characters
     $pattern .= '\\x{0600}-\\x{06FF}';
     $pattern .= '\\x{FB50}-\\x{FDFD}';
     $pattern .= '\\x{FE70}-\\x{FEFF}';
     $pattern .= '\\x{0750}-\\x{077F}';
     $pattern .= ']+';
     $this->router->addMatchTypes(array('nonArabic' => $pattern));
     $this->router->map('GET', '/bar/[nonArabic:string]', 'non_arabic_action', 'non_arabic_route');
     $this->assertEquals(array('target' => 'non_arabic_action', 'name' => 'non_arabic_route', 'params' => array('string' => 'some-path')), $this->router->match('/bar/some-path', 'GET'));
     $this->assertFalse($this->router->match('/﷽‎', 'GET'));
 }
Example #9
0
 /**
  * This function runs the router and call the apropriate
  */
 public function run($url = null, $method = null)
 {
     $route = $this->altoRouter->match($url, $method);
     if (!$route) {
         throw new NotFoundException((isset($_SERVER['REQUEST_URI']) && !empty($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : ($url != null ? $url : "/")) . " is not reachable.");
     }
     if (!isset($route['target']['c']) || !isset($route['target']['a']) || !isset($route['params'])) {
         throw new FrameworkException('Internal Framework Error. [!BAD_ROUTER_TARGET]', 01);
     }
     if (is_callable(array($route['target']['c'], 'getInstance'))) {
         $controller = $route['target']['c']::getInstance();
         if (method_exists($controller, $route['target']['a'])) {
             call_user_func(array($controller, $route['target']['a']), array_values($route['params']));
             $controller->response->send();
         } else {
             throw new FrameworkException('Internal Framework Error. [METHOD_DOES_NOT_EXISTS]', 02);
         }
     } else {
         throw new FrameworkException('Internal Framework Error. [CONTROLLER_DOES_NOT_EXISTS]', 03);
     }
 }
Example #10
0
<?php

/*
  Answer to the questions{

  1) If the size of memory will hit its limit we will need to do either vertical extension until we reach hardware limits and then horizontal extension and then we will face problems of sharding and script performance analysis. Though, we can extend time before that will happen. We can store all our data in DB, like MySQL, and set proper INDEX there, so DB will look for it faster and will take up less memory. Than what I implemented here.
  2) If we hit limits of request processing - we will have to do vertical or horizontal extension. We can try develop queueing and job scripts. But that has another problems. What I mean is that even if we do queueing, hardware will face its limits in queue and then fail. We can cut out requests for some time, until queue gets a little freed up, but it all depends on how much business company ready to cut down versus how much can be invested
  3) I have developed API for update and used routing semi-framework to redirect all update queries there. We can use cRon for scheduling task and performing on a set of data update script every n minutes. Or we can have Scheduler Server which works this script by schedule. I have hardware limitations to reproduce either of these solutions

  All responses are returned in JSON for future development jQuery or any other JS libriary can connect and get JSON answer and work it around. Or an application on a mobile phone.
}
*/
header("Content-Type: text/html");
include $_SERVER["DOCUMENT_ROOT"] . '/include/AltoRouter.php';
$router = new AltoRouter();
$router->setBasePath('');
/* Setup the URL routing. This is production ready. */
// Main routes that non-customers see
$router->map('GET', '/urlinfo/[1:action]/[*:url]', 'urlinfo/index.php', "check-data");
$router->map('GET', '/urlinfo/[update:action]/[*:url]/[false|true:safe]', 'urlinfo/index.php', "update-data");
/* Match the current request */
// call closure or throw 404 status
$match = $router->match();
if ($match) {
    require $match['target'];
} else {
    header($_SERVER["SERVER_PROTOCOL"] . ' 404 Not Found');
}
Example #11
0
<?php

/**
 * write by vyouzhi 
 */
include_once 'bootstrap.php';
$router = new AltoRouter();
$router->setBasePath(ROOT);
foreach ($routeMap as $value) {
    $router->map($value['method'], $value['uri'], $value['params'], $value['module']);
}
$router->AutoLoad();
$match = $router->match();
$router->httpCode301();
//$router->httpCode404($match);
routing($match['action']);
if (class_exists($match['action'])) {
    $show = new $match['action']();
    $show->Show();
} else {
    require_once Lib . '/error/e404.php';
    $show = new e404();
    $show->Show();
    //如果没有就直接 404
    //$router->httpCode404(false);
}
?>

Example #12
0
define("render_template", global_path . "app/views/");
define("render_partial", global_path . "app/views/partials/");
define("stylesheet_tag", global_path . "app/assets/css/");
define("javascript_include", global_path . "app/assets/js/");
define("include_vendor", global_path . "vendor/");
define("include_lib", global_path . "lib/");
define("include_model", global_path . "app/models/");
define("include_controller", global_path . "app/controllers/");
//add dependencies
define("FACEBOOK_SDK_V4_SRC_DIR", "./vendor/facebook-php-sdk-v4.4.0-dev/src/Facebook/");
//
session_start();
//add autoload.php
require global_path . "autoload.php";
// router
$router = new AltoRouter();
$data = array('helper' => $helper, 'scopes' => $application['general']['facebook']['scopes']);
$router->map('GET', '/', $HomeController->index($data));
$match = $router->match();
if ($match && is_callable($match['target'])) {
    call_user_func_array($match['target'], $match['params']);
} else {
    // no route was matched
    header($_SERVER["SERVER_PROTOCOL"] . ' 404 Not Found');
}
/**$uri = $_SERVER['REQUEST_URI'];

    if($uri == "/" || $uri == "/index.php"):
      $data = array(
        'helper' => $helper,
        'scopes' => $application['general']['facebook']['scopes']
Example #13
0
 /**
  * Match a given request url against stored routes
  *
  * @param string $request_url
  * @param string $request_method
  *
  * @return array boolean with route information on success, false on failure (no match).
  */
 public function match($request_url = null, $request_method = null)
 {
     // Set Request Url if it isn't passed as parameter
     if ($request_url === null) {
         $request_url = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '/';
     }
     $this->request_url = $request_url;
     // Set Request Method if it isn't passed as a parameter
     if ($request_method === null) {
         $request_method = isset($_SERVER['REQUEST_METHOD']) ? $_SERVER['REQUEST_METHOD'] : 'GET';
     }
     // Is this an ajax request?
     if (substr($request_url, -5) == '/ajax') {
         $this->ajax = true;
         $request_url = str_replace('/ajax', '', $request_url);
     } elseif (isset($_GET['ajax'])) {
         $this->ajax = true;
     }
     $this->match = parent::match($request_url, $request_method);
     if (!empty($this->match)) {
         // Some parameters only have control or workflow character and are no parameters for public use.
         // Those will be removed from the parameters array after using them to set corresponding values and/or flags
         // in router.
         $controls = ['ajax', 'format'];
         foreach ($controls as $key) {
             if (isset($this->match['params'][$key])) {
                 switch ($key) {
                     case 'ajax':
                         $this->ajax = true;
                         break;
                     case 'format':
                         $this->format = $this->match['params'][$key];
                         break;
                     default:
                         $this->{$key} = $this->match['params'][$key];
                 }
                 break;
             }
             unset($this->match['params'][$key]);
         }
     }
     if (!empty($this->match['params'])) {
         foreach ($this->match['params'] as $key => $val) {
             if (empty($val)) {
                 unset($this->match['params'][$key]);
             }
             if (in_array($key, $this->parameter_to_target)) {
                 $this->match['target'][$key] = $val;
             }
         }
     }
 }
    //Construcción de array para json
    $data_post[] = array('type' => 'twitter', 'content' => $statuse['text'], 'date' => $date_format, 'likes' => $statuse['favorite_count']);
}
//fin twitter
//Instagram
$http = new HttpConnection();
$http->init();
$data_instagram = json_decode($http->get("https://api.instagram.com/v1/tags/meat/media/recent?access_token=44110995.1677ed0.6d87a7ce19f544c99e2912686465de59&count=25"), true);
$http->close();
foreach ($data_instagram['data'] as $data) {
    //Formato a fecha
    $horas_restantes = 4;
    $date_format = $data['created_time'] - $horas_restantes * 3600;
    $date_format = date('d/m/Y H:i:s', $date_format);
    //Construcción de array para json
    $data_post[] = array('type' => 'instagram', 'content' => $data['images']['standard_resolution']['url'] . ' ' . $data['caption']['text'], 'date' => $date_format, 'likes' => $data['likes']['count']);
}
//fin instagram
//Router
$router = new AltoRouter();
$router->setBasePath('');
$router->map('GET', '/posts', 'posts.php', 'posts');
$router->map('GET', '/posts/likes', 'likes.php', 'likes');
$match = $router->match();
if ($match) {
    require $match['target'];
} else {
    header("HTTP/1.0 404 Not Found");
    require '404.php';
}
//fin router
Example #15
0
<?php

require 'vendor/autoload.php';
// Create a Primer instance
$primer = (require_once __DIR__ . '/bootstrap/start.php');
// Create a router object
$router = new AltoRouter();
/**
 * Match the home page, show the full list of patterns
 */
$router->map('GET', '/', function () use($primer) {
    $primer->showAllPatterns(!isset($_GET['minimal']));
});
/**
 * Match the routes for showing individual patterns
 */
$router->map('GET', '/patterns/[**:trailing]', function ($ids) use($primer) {
    // Enable multiple patterns to be displayed, seperated by ':' characters
    $ids = explode(':', $ids);
    // Show the patterns
    $primer->showPatterns($ids, !isset($_GET['minimal']));
});
/**
 * Match the routes for showing specific templates
 */
$router->map('GET', '/templates/[**:trailing]', function ($id) use($primer) {
    // Show the template
    $primer->showTemplate($id);
});
/**
 * Match the routes for retrieving the list of page templates
Example #16
0
<?php

require_once __DIR__ . "/../../FMA/autoload.php";
header("Content-Type: application/json");
$_pdo = new \FMA\PDO\MySQL_PDO();
$router = new AltoRouter([], "/api");
if (!\FMA\Utility::isDevServer()) {
    $router->map("GET", "[*]", function () use($_pdo) {
        return ["err" => true, "msg" => "API is still under development."];
    });
} else {
    $router->map("GET", "/organization/", function () use($_pdo) {
        return \FMA\Organization\GreekOrganization::allAsArray($_pdo);
    });
    $router->map("GET", "/organization/[i:id]/", function ($id) use($_pdo) {
        $org = \FMA\Organization\GreekOrganization::find($_pdo, $id);
        if (is_null($org)) {
            return ["err" => true, "msg" => "No organization by that id."];
        }
        return $org->toArray();
    });
    $router->map("GET", "/organization/[i:id]/chapter/", function ($id) use($_pdo) {
        $org = \FMA\Organization\GreekOrganization::find($_pdo, $id);
        if (is_null($org)) {
            return ["err" => true, "msg" => "No organization by that id."];
        }
        return \FMA\Organization\Chapter::findAllForGreekOrganizationAsArray($_pdo, $org);
    });
    $router->map("GET", "/organization/[i:id]/chapter/[i:cid]/", function ($id, $cid) use($_pdo) {
        $org = \FMA\Organization\GreekOrganization::find($_pdo, $id);
        if (is_null($org)) {
Example #17
0
 /**
  * Run this application
  *
  * @return  mixed
  */
 public function run()
 {
     // Collect routes
     $this->router->addRoutes($this->collectRoutes());
     return $this->callController();
 }
Example #18
0
<?php

require_once __DIR__ . "/../../FMA/autoload.php";
error_reporting(0);
$_pdo = new \FMA\PDO\MySQL_PDO();
$_auth = new \FMA\Auth\SessionAuth($_pdo);
$router = new AltoRouter([], "/image");
$_fs = \FMA\Config::getFileSystem();
$router->map("GET", "/profile/[small|medium|large:size]/[i:id]/", function ($size, $id) use($_pdo, $_fs, $_auth) {
    $user = \FMA\User\User::find($_pdo, $id);
    if (is_null($user)) {
        return;
    }
    $img = $user->getImageFile($_fs);
    $file_name = strtolower($user->getNameFirst() . "-" . $user->getNameLast() . "." . $img->getExtension());
    header("Content-Disposition: inline; filename=\"" . $file_name . "\"");
    if (is_null($img) || !$img->isImage()) {
        return;
    }
    $_im = \FMA\Image\GDImageManipulator::read($img);
    if ($size == "medium") {
        $_im->resize("50%", "50%");
    } else {
        if ($size == "small") {
            $_im->resize("25%", "25%");
        }
    }
    $_im->output($img->getExtension());
});
$match = $router->match();
if ($match && !is_callable($match["target"])) {
Example #19
0
<?php

header("Content-Type: text/html");
include $_SERVER["DOCUMENT_ROOT"] . '/include/AltoRouter.php';
$router = new AltoRouter();
$className = "";
$classMethod = "";
$router->setBasePath('');
/* Setup the URL routing. This is production ready. */
// Main routes that non-customers see
$router->map('GET', '/[products:action]', 'api/sync.php', "return-data");
$router->map('GET', '/[sync:action]', 'api/sync.php', 'home-home');
$router->map('GET', '/[products:action]/[i:id]', 'api/sync.php', "return-data-with-id");
//$router->map('GET', '/api/products/[i:id]', '/api/retrieve.php')
/* Match the current request */
// call closure or throw 404 status
$match = $router->match();
if ($match) {
    require $match['target'];
} else {
    header($_SERVER["SERVER_PROTOCOL"] . ' 404 Not Found');
}
Example #20
0
<?php

session_start();
define('BASE_URL', 'http://' . $_SERVER['HTTP_HOST'] . '/SENIOR/frontend/');
require '../backend/classes/AltoRouter.php';
$router = new AltoRouter();
$router->setBasePath('/SENIOR/frontend');
//Index
$router->map('GET|POST', '/', 'home.php');
//BACKEND
$router->map('GET|POST', '/admin', '../backend/login.php', 'admin');
$router->map('GET|POST', '/G-admin', '../backend/indexBE.php', 'adminLogged');
// Items portfolio
$router->map('GET|POST', '/G-admin/portfolio', '../backend/imagenesPortfolio.php', 'portfolio');
$router->map('GET|POST', '/G-admin/alta-item', '../backend/services/itemsPortfolio/altaItemProject.php', 'altaItemProject');
$router->map('GET|POST', '/G-admin/alta-item/subirfoto', '../backend/services/itemsPortfolio/uploads.php', 'subirfotos');
$router->map('GET|POST', '/G-admin/services/listarItems', '../backend/services/itemsPortfolio/listarItems.php', 'listarItems');
$router->map('GET|POST', '/G-admin/portfolio/nuevo', '../backend/services/itemsPortfolio/nuevo.php', 'nuevoItem');
$router->map('GET|POST', '/G-admin/portfolio/[*:titPro]/', '../backend/services/itemsPortfolio/item.php', 'itemPortfolio');
$router->map('GET|POST', '/G-admin/modificar/[*:idItem]/[*:titPro]', '../backend/services/itemsPortfolio/modificarItem.php', 'modificarItem');
$router->map('GET|POST', '/G-admin/modificar/[*:idItem]/[*:titPro]', '../backend/services/itemsPortfolio/borrarItem.php', 'borrarItem');
//$router->map('GET|POST','/G-admin/services/eliminarItems', '../backend/services/itemsPortfolio/eliminar.php', 'eliminarItems');
//$router->map('GET|POST','/G-admin/services/eliminarItems/[i:idItem]', '../backend/services/itemsPortfolio/eliminar.php', 'eliminarItems');
// Páginas
$router->map('GET|POST', '/G-admin/paginas', '../backend/services/loadPage.php', 'paginas');
$router->map('GET|POST', '/G-admin/proyectos', '../backend/services/listarProyectos.php', 'proyectos');
$router->map('GET|POST', '/G-admin/nueva-pagina', '../backend/services/newPage.php', 'nuevaPag');
$router->map('GET|POST', '/G-admin/alta-pagina', '../backend/services/altaPag.php', 'altaPag');
// Bloques
$router->map('GET|POST', '/G-admin/nuevo-bloque', '../backend/services/newBlock.php', 'nuevoBloque');
$router->map('GET|POST', '/G-admin/alta-bloque', '../backend/services/altaBlock.php', 'altaBlock');
Example #21
0
    }
});
// grab the settings
require ROOT . 'settings.php';
// grab status definitions
require SCRIPTROOT . 'statusdefs.php';
// set timezone
date_default_timezone_set('UTC');
// setup cache
require SCRIPTROOT . 'phpfastcache/phpfastcache.php';
phpFastCache::setup('storage', 'files');
phpFastCache::setup('path', ROOT . 'cache');
$cache = phpFastCache();
// setup routing
require SCRIPTROOT . 'AltoRouter/AltoRouter.php';
$routes = new AltoRouter();
// load the actual routes
require ROOT . 'routes.php';
// handle the route request
$route = $routes->match();
// error page handling
function ErrorPage($Error)
{
    ob_get_clean();
    http_response_code($Error);
    $error = $Error;
    require VIEWROOT . 'error.php';
    die;
}
if (!$route) {
    ErrorPage(404);
Example #22
0
<?php

require_once __DIR__ . "/../FMA/autoload.php";
$_pdo = new \FMA\PDO\MySQL_PDO();
$_auth = new \FMA\Auth\SessionAuth($_pdo);
$router = new AltoRouter();
$router->map("GET", "/", function () use($_pdo, $_auth) {
    $_auth->validate();
    require __DIR__ . "/../views/home.php";
}, "Home");
$router->map("GET", "/login/", function () use($_pdo, $_auth) {
    $_auth->validate(true);
    require __DIR__ . "/../views/login.php";
}, "Login");
$router->map("GET", "/logout/", function () use($_pdo, $_auth) {
    $_auth->logout();
}, "Logout");
$router->map("GET", "/account/confirm/[*:token]/", function ($token) use($_pdo, $_auth) {
    $_GET["t"] = $token;
    $controller = new \FMA\Controllers\UserVerificationController($_pdo);
    $controller->main();
    require __DIR__ . "/../views/validate_account.php";
}, "Account");
$router->map("GET", "/calendar/", function () use($_pdo, $_auth) {
    $_auth->validate();
    require __DIR__ . "/../views/calendar.php";
}, "Calendar");
if (\FMA\Utility::isDevServer()) {
    $router->map("GET", "/test/", function () use($_pdo, $_auth) {
        require __DIR__ . "/../views/test.php";
    }, "Test");
Example #23
0
<?php

/**
 * @author Tran Hoang Hiep
 * @copyright 2015
 */
require 'vendor/AltoRouter.php';
global $db;
$router = new AltoRouter();
//Home Page Routes
//method, URI, Target, Param, Name
$router->map('GET', '/', array('c' => 'HomeController', 'a' => 'IndexAction'), 'HomePage');
//Login Routes
$router->map('GET|POST', '/login', array('c' => 'LoginController', 'a' => 'LoginAction'), 'LoginPage');
$router->map('GET', '/logout', array('c' => 'LoginController', 'a' => 'LogoutAction'), 'LogoutPage');
$router->map('POST', '/lost-password', array('c' => 'LoginController', 'a' => 'LostPasswordAction'), 'LostPasswordPage');
//CRM - Customer Relation Management Routes
//RMA - Return Material Assistant Routes
//CSM - Customer Saller Management Routes
//Hiển thị thông tin người dùng
$router->map('GET', '/users/[i:id]', array('c' => 'UserController', 'a' => 'ListAction'), 'users_show');
// match current request url
$match = $router->match();
//enforce all user must login!
if (!isset($_SESSION['user']) && !($match['name'] == "LoginPage" || $match['name'] == "LogoutPage")) {
    header('Location: ' . $_SITE_DOMAIN . '/login');
}
if (!isset($match['target']['c'])) {
    header($_SERVER["SERVER_PROTOCOL"] . ' 404 Server Error', true, 404);
}
switch ($match['target']['c']) {
Example #24
0
<?php

/**
 * Created by PhpStorm.
 * User: Saleh Saeed
 * Date: 1/23/2016
 * Time: 11:22 PM
 */
require_once "vendor/autoload.php";
$router = new AltoRouter();
$router->map('GET', '/', function () {
    require_once "App/Views/index.php";
}, 'home');
// match current request url
$match = $router->match();
// call closure or throw 404 status
if ($match && is_callable($match['target'])) {
    call_user_func_array($match['target'], $match['params']);
} else {
    // no route was matched
    header($_SERVER["SERVER_PROTOCOL"] . ' 404 Not Found');
    die('404 Not Found');
}
Example #25
0
<?php

header('Content-type: application/json');
include_once '../bootstrap.php';
$apiRouter = new AltoRouter();
$apiRouter->setBasePath(substr(Config::get('basedir') . 'api/', 0, -1));
// ROUTER MAPPING
// AUTH TOKEN
$apiRouter->map('POST', '/app/create', array('c' => 'App', 'a' => 'create', 'authtoken' => false, 'usertoken' => false, 'official' => false));
$apiRouter->map('POST', '/authtoken/create', array('c' => 'AuthToken', 'a' => 'create', 'authtoken' => false, 'usertoken' => false, 'official' => false));
$apiRouter->map('POST', '/usertoken/create', array('c' => 'UserToken', 'a' => 'create', 'authtoken' => true, 'usertoken' => false, 'official' => true));
// USER
$apiRouter->map('POST|GET', '/user/hastrained', array('c' => 'User', 'a' => 'hasTrained', 'authtoken' => true, 'usertoken' => true, 'official' => true));
$apiRouter->map('POST|GET', '/user/train', array('c' => 'User', 'a' => 'train', 'authtoken' => true, 'usertoken' => true, 'official' => true));
$apiRouter->map('POST', '/user/create', array('c' => 'User', 'a' => 'create', 'authtoken' => true, 'usertoken' => false, 'official' => true));
$apiRouter->map('GET', '/user/get', array('c' => 'User', 'a' => 'get', 'authtoken' => true, 'usertoken' => true, 'official' => false));
// JOB
$apiRouter->map('POST|GET', '/job/get', array('c' => 'Job', 'a' => 'get', 'authtoken' => true, 'usertoken' => true, 'official' => false));
$apiRouter->map('POST|GET', '/job/work', array('c' => 'Job', 'a' => 'work', 'authtoken' => true, 'usertoken' => true, 'official' => true));
// MARKET
$apiRouter->map('POST', '/market/job/apply', array('c' => 'JobMarket', 'a' => 'apply', 'authtoken' => true, 'usertoken' => true, 'official' => false));
$apiRouter->map('POST', '/market/job/create', array('c' => 'JobMarket', 'a' => 'create', 'authtoken' => true, 'usertoken' => true, 'official' => true));
$apiRouter->map('POST', '/market/job/offers', array('c' => 'JobMarket', 'a' => 'offers'));
// COMPANY
$apiRouter->map('POST', '/company/get', array('c' => 'Company', 'a' => 'get', 'authtoken' => true, 'usertoken' => true));
$apiRouter->map('POST', '/company/create', array('c' => 'Company', 'a' => 'create', 'authtoken' => true, 'usertoken' => true, 'official' => true));
$apiRouter->map('POST|GET', '/company/list', array('c' => 'Company', 'a' => 'getList', 'authtoken' => true, 'usertoken' => true));
// RESOURCE
$apiRouter->map('GET', '/resource/get', array('c' => 'Resource', 'a' => 'get'));
$apiRouter->map('GET', '/resource/list', array('c' => 'Resource', 'a' => 'getList'));
$apiRouter->map('POST', '/resource/create', array('c' => 'Resource', 'a' => 'create'));
Example #26
0
<?php

// Import our modules
require __DIR__ . '/modules/AltoRouter/AltoRouter.php';
require __DIR__ . '/modules/h2o-php/h2o.php';
require __DIR__ . '/modules/UTSHelpsAPI/UTSHelpsAPI.php';
require __DIR__ . '/modules/mandrill/Mandrill.php';
// Import our models
require __DIR__ . '/models/autoload.php';
// Import our config files
require __DIR__ . '/config/session.php';
require __DIR__ . '/config/config.php';
$router = new AltoRouter();
require __DIR__ . '/config/routes.php';
$match = $router->match();
header("X-Processed-By: AltoRouter");
if ($match && is_callable($match['target'])) {
    call_user_func_array($match['target'], $match['params']);
} else {
    Session::redirect('/404');
}
Example #27
0
<?php
/*
//  / This file handles the initial request to the server
//  / It's checks for the product type and returns a different element to the client 
//  / depending on what was requested
// */

// this is has the path to the root dir - it's useful if we move this file since we only need update the path once
include 'init.php';

include ROOT_DIR .  '/vendor/altorouter/altorouter/AltoRouter.php';
$router = new AltoRouter();

// print_r($router);

// echo 'stat';
// $router->map( 'GET', '/', 'render_home', 'home' );

// map homepage using callable
$router->map( 'GET', '/', function() {
  require ROOT_DIR . '/views/home.php';
});

$match = $router->match();

print_r($match);

// call closure or throw 404 status
if( $match && is_callable( $match['target'] ) ) {
  echo 'dsfsd';
  call_user_func_array( $match['target'], $match['params'] ); 
 /**
  * Démarrage de l'application.
  */
 public function run()
 {
     $router = new \AltoRouter();
     if (isset($_SERVER['BASE'])) {
         $router->setBasePath($_SERVER['BASE']);
     }
     $router->map('GET', '/', function () {
         $this->startControllerAction('Public', 'index');
     }, 'home');
     $router->map('GET|POST|PATCH|PUT|DELETE', '/[a:controller]/[a:action]', function ($controller, $action) {
         $this->startControllerAction(ucfirst($controller), $action);
     }, 'action');
     if (($match = $router->match()) !== false) {
         call_user_func_array($match['target'], $match['params']);
     } else {
         header("{$_SERVER['SERVER_PROTOCOL']} 404 Not Found");
     }
 }
Example #29
0
<?php

require 'vendor/autoload.php';
// Import the necessary classes
use Illuminate\Database\Capsule\Manager as Capsule;
// Include the composer autoload file
// Setup a new Eloquent Capsule instance
$capsule = new Capsule();
$capsule->addConnection(['driver' => 'mysql', 'host' => '127.0.0.1', 'database' => 'cs', 'username' => 'root', 'password' => '', 'charset' => 'utf8', 'collation' => 'utf8_unicode_ci']);
$capsule->bootEloquent();
$router = new AltoRouter();
$router->setBasePath('/cs');
$router->map('GET|POST', '/', 'home#index', 'home');
$router->map('GET', '/users/', array('c' => 'UserController', 'a' => 'ListAction'));
$router->map('GET', '/api/course/all/', 'Api#allCourses');
$router->map('GET', '/api/course/[i:id]/', 'Api#getCourse');
$router->map('GET', '/api/user/all/', 'Api#allUsers');
$router->map('POST', '/api/user/new/', 'Api#newUser');
$router->map('GET', '/api/user/[*:id]/', 'Api#getUser');
$router->map('GET', '/api/cron/', 'Api#cron');
// match current request
$match = $router->match();
if ($match) {
    $path = explode('#', $match['target']);
    $controller = $path[0];
    $method = $path[1];
    $params = $match['params'];
    $object = new $controller();
    $object->{$method}($params);
} else {
    (new Controller())->index();
<?php

require_once __DIR__ . '/../vendor/autoload.php';
require_once dirname(__FILE__) . '/../config/db.php';
require_once dirname(__FILE__) . '/../src/User.php';
$conn = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_DB, DB_PORT);
if ($conn->connect_error) {
    $error = $conn->connect_error . '(' . $conn->connect_errno . ')';
    echo $error;
} else {
    $conn->set_charset('utf8');
}
//tworzymy nowy obiekt AltoRouter
$router = new AltoRouter();
//z db.php bierzemy base_path, ktory jest naszym katalogiem glownym po ktorym bedziemy otrzymywac ladne slashe
$router->setBasePath(BASE_PATH);
include dirname(__FILE__) . '/../routing.php';
$match = $router->match();
//uruchamia nam nasz router i automatycznie dodaje go do kazdej podstrony
if ($match) {
    require '../' . $match['target'];
} else {
    echo "nie ma strony";
}
User::setConnection($conn);