Exemplo n.º 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']);
     }
 }
Exemplo n.º 2
1
 /**
  * Adds a new route to the routes collection.
  *
  * @param string $httpMethods
  * @param string $route
  * @param string $action
  * @param null $name
  * @return mixed
  * @throws \Exception
  */
 public function add($httpMethods, $route, $action, $name = null)
 {
     $_route = $this->normalizeRoute($route);
     if (!$this->isValidAction($action)) {
         throw new \Exception(sprintf("Invalid action '%s'. Are you using '%s' as controller/action separator?", $action, self::DEFAULT_CONTROLLER_ACTION_SEPARATOR));
     }
     $this->altoRouter->map($httpMethods, $_route, $action, $name);
     return $this;
 }
Exemplo n.º 3
1
<?php

require 'vendor/autoload.php';
$router = new AltoRouter();
$router->setBasePath('/alto-app/');
$router->map('GET', '/users/[i:id]/', 'UserController#showDetails');
$match = $router->match();
use App\Auth\User;
use App\Orders\User as UserOrder;
$u = new User();
$u = new UserOrder();
new App\A\Test();
new App\B\Test();
Exemplo n.º 4
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'));
 }
Exemplo n.º 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;
 }
Exemplo n.º 6
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'));
 }
Exemplo n.º 7
0
error_reporting(E_ERROR | E_WARNING | E_PARSE);
ini_set('display_errors', 'On');
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}
$api_folder = "apiv2";
$root = dirname(__FILE__);
require $root . "/inc/config.php";
require $root . '/inc/AltoRouter.php';
//require $root . '/' . $api_folder . '/class/user.php';
$router = new AltoRouter();
//$user = new User();
//$router->setBasePath("/");
//Login Page
$router->map('GET', '/', 'View::render#Login', 'login');
//Course
$router->map('GET', '/course/', 'View::render#Course', 'course');
$router->map('GET', '/course/[i:course_id]/', 'View::render#Course_Detail', 'course_detail');
$router->map('GET', '/course/add/', 'View::render#Course_New', 'course_new');
$router->map('GET', '/questionbank/', 'View::render#Question_Bank', 'questionbank');
$router->map('GET', '/assignment/[i:assignment_id]/', 'View::render#Assignment', 'assignment');
//Teacher Assignment
$router->map('GET', '/assignment/add/[i:course_id]/', 'View::render#Assignment_New', 'assignment_new');
$router->map('GET', '/assignment/edit/[i:assignment_id]/', 'View::render#Assignment_Edit', 'assignment_edit');
$router->map('GET', '/assignment/edit/testcase/[i:assignment_id]/', 'View::render#Assignment_Testcase_Edit', 'assignment_edit_testcase');
$router->map('GET', '/statistics/overall/[i:assignment_id]/', 'View::render#Assignment_Overall_Statistics', 'overall_stat');
$router->map('GET', '/statistics/[i:assignment_id]/', 'View::render#Assignment_Statistics', 'assignment_stat');
$router->map('GET', '/statistics/[i:assignment_id]/group/[i:group_id]/', 'View::render#Assignment_Group_Statistics', 'assignment_group_stat');
$router->map('GET', '/datamining/[i:assignment_id]/', 'View::render#Assignment_Data_Mining', 'data_mining');
//Assignment Do
Exemplo n.º 8
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');
Exemplo n.º 9
0
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']
        );
      $HomeController->index($data);
Exemplo n.º 10
0
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"])) {
    throw new TypeError("Target is not callable.");
} else {
    if ($match && is_callable($match["target"])) {
Exemplo n.º 11
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");
Exemplo n.º 12
0
// # Mailer instance
$Mailer = new PHPMailer();
// # ChartsBuilder instance
$CB = new ChartsBuilder($PM, $log);
// # Initializing router
$router = new AltoRouter();
// # This app is deployed in production as a subfolder and not a virtualhost
// # so we need to set a basepath for prod environment
if ($PM->getproperty('env') == 'prod') {
    $router->setBasePath('/suncharts/');
}
// # $Params default
$defaults = array('y' => date('Y'), 'm' => date('m'), 'oTypeID' => 1, 'oID' => 'All', 'techID' => 'All', 'oVendorID' => 'All', 'countryID' => 'IT');
// # Config interface
$router->map('GET', '/', function () {
    // # Shows the page
    require_once "config.html";
});
// # Cron based call ( all params are set to defaults )
$router->map('GET', 'worker/default', function () use($PM, $DAOConn, $log, $CB, $defaults) {
    // # Unlink latest charts files
    $CB->clearPast();
    // # Response
    $SR = new ServiceResponse();
    try {
        // # Connect to db
        $DAO = new DAO($DAOConn, $log);
        // # re
        $RSByoID = $DAO->getLabWorkloadByoID($defaults['y'], $defaults['oTypeID'], $defaults['oID'], $defaults['countryID']);
        $RSByTechnician = $DAO->getLabWorkloadByTechnician($defaults['y'], $defaults['m'], $defaults['countryID']);
        $RSByMonth = $DAO->getLabWorkloadByMonth($defaults['y'], $defaults['m'], $defaults['countryID']);
        // # Build chart
Exemplo n.º 13
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)) {
Exemplo n.º 14
0
<?php

// Really simple weather data (xml) to JSON array parser for (regional) Australian Bureau of Meterology weather data
// Could easily be adapted to handle other XML files on the anonymous FTP (and probably on the authenticated FTP $$$)
require_once 'vendor/autoload.php';
header("Content-Type: Application/JSON");
$router = new AltoRouter();
$router->map('GET', '/', function () {
    echo json_encode("No source selected. Tail this url with a lowercase Australian capital city. (ex: adelaide.json)", 128);
});
$router->map('GET', '/[:location].json', function ($location) {
    $locationsArray = array("adelaide" => "ftp://ftp2.bom.gov.au/anon/gen/fwo/IDS65176.xml", "canberra" => "ftp://ftp2.bom.gov.au/anon/gen/fwo/IDN65176.xml", "sydney" => "ftp://ftp2.bom.gov.au/anon/gen/fwo/IDN65176.xml", "melbourne" => "ftp://ftp2.bom.gov.au/anon/gen/fwo/IDV65176.xml", "brisbane" => "ftp://ftp2.bom.gov.au/anon/gen/fwo/IDQ60604.xml", "perth" => "ftp://ftp2.bom.gov.au/anon/gen/fwo/IDW65176.xml", "hobart" => "ftp://ftp2.bom.gov.au/anon/gen/fwo/IDT65176.xml", "darwin" => "ftp://ftp2.bom.gov.au/anon/gen/fwo/IDD65176.xml");
    if ($locationsArray[$location]) {
        $dataSource = file_get_contents($locationsArray[$location]);
        if ($dataSource) {
            $xml = simplexml_load_string($dataSource);
            if ($xml) {
                $json = json_encode($xml, 128);
                if ($json) {
                    $CleanIn = json_decode($json, true);
                    $CleanOut = array();
                    $count = 0;
                    foreach ($CleanIn[product][group][obs] as $observation) {
                        $stationName = $observation["@attributes"]["station"];
                        $station = array("Time updated" => $observation["@attributes"]["obs-time-local"], "Maximum temperature" => floatval($observation[d][0]), "Minimum temperature" => floatval($observation[d][1]), "Terrestrial minimum temperature" => floatval($observation[d][2]), "Wetbulb depression" => floatval($observation[d][3]), "Rain" => floatval($observation[d][4]), "Evaporation" => floatval($observation[d][5]), "Wind run" => floatval($observation[d][6]), "Sunshine" => floatval($observation[d][7]), "Solar radiation" => floatval($observation[d][8]), "5cm temperature" => floatval($observation[d][9]));
                        array_push($CleanOut, array("{$stationName}" => $station));
                        $count++;
                    }
                    array_push($CleanOut, array("Total Stations" => $count));
                    echo json_encode($CleanOut, 128);
                } else {
Exemplo n.º 15
0
<?php

$base = "./";
// NIVs
date_default_timezone_set('UTC');
// Classes, vendor
require './vendor/autoload.php';
require './classes/autoinclude.php';
// Router follows...
$router = new AltoRouter();
// Index
$router->map('GET', '/', function () {
    $tmpPresentation = new tmpPresentation();
    echo $tmpPresentation->generatePage("TfEL Maths Pedagogy", "<h3>TfEL Maths Pedagogy <small>Shared Reflection API</small></h3> <p>Expects arguments on <code>/s/</code> or <code>/a/</code>.</p><p><strong>Here by accident?</strong><br>You probably followed a broken link to someone's shared observation. Ask them to send you the link again.</p><p><strong>Still totally lost?</strong><br>We can help you figure out where you need to go, email <code>DECD.TfEL@sa.gov.au</code>.")->page;
});
// Addition
$router->map('POST|PUT', '/a/v[i:version]/[:token]', function ($version, $token) {
    header("Content-Type: application/json");
    $tokens = new Tokens();
    if ($tokens->verifyToken($token) && $version == 1) {
        $shareData = new shareData();
        $return = $shareData->createShare(file_get_contents('php://input'));
        if (!$return) {
            echo json_encode("Failed to create share URL.");
        } else {
            echo json_encode($return);
        }
    } else {
        echo json_encode("Invalid token, or outdated app.");
    }
});
Exemplo n.º 16
0
<?php

require_once "vendor/autoload.php";
$router = new AltoRouter();
$pdo = new PDO("mysql:host=localhost;dbname=alto", "root", "root");
$conn = new NotOrm($pdo);
$match = $router->match();
$router->map('GET', '/buku', function () use($router, $conn) {
    $bukus = $conn->buku();
    $data = [];
    foreach ($bukus as $buku) {
        $data[] = $buku;
    }
    header("HTTP/1.1 200 Ok");
    echo json_encode($data);
});
$router->map('GET', '/buku/[i:id]', function ($id) use($router, $conn) {
    $buku = $conn->buku[$id['id']];
    if ($buku) {
        echo json_decode($buku);
        header("HTTP/1.1 200 Ok");
    } else {
        header("HTTP/1.1 404 No Found");
        echo json_encode(['message' => 'Not Found']);
    }
});
$router->map('POST', '/buku', function () use($router, $conn) {
    $data = json_decode($_POST['data']);
    $buku = $conn->buku()->insert(array("name" => $data->nama, "price" => $data->price, "image" => $data->image));
    if (!$buku) {
        header("HTTP/1.1 400 Bad Request");
Exemplo n.º 17
0
<?php

use Otik\Config;
use Tracy\Debugger;
use Otik\Output;
require_once 'vendor/autoload.php';
$config = new Config(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'config');
Debugger::enable(Debugger::DETECT, dirname(__FILE__) . DIRECTORY_SEPARATOR . 'log', $config->get('dev.email'));
$router = new AltoRouter();
$router->map('OPTIONS', '/series/[*:series]/events', 'Options::optionsForEvents', 'optionsForEvents');
$router->map('POST', '/series/[*:series]/events', 'Event::postToEvents', 'postToEvents');
if (isset($_REQUEST['_method'])) {
    $matched = $router->match(null, $_REQUEST['_method']);
} else {
    $matched = $router->match();
}
if ($matched === false) {
    $o = new Output();
    $o->return404();
}
list($wantedController, $wantedAction) = explode('::', $matched['target']);
$controllerClassName = 'Otik\\' . $wantedController;
if (!class_exists($controllerClassName)) {
    throw new RuntimeException('Target class (' . $controllerClassName . ') doesn\'t exists or cann\'t be autoloaded');
}
$controller = new $controllerClassName($config);
if (!method_exists($controller, $wantedAction)) {
    throw new RuntimeException('Target class doesn\'t have method ' . $wantedAction . '.');
}
call_user_func_array(array($controller, $wantedAction), $matched['params']);
Exemplo n.º 18
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();
Exemplo n.º 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');
}
Exemplo n.º 20
0
    //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
Exemplo n.º 21
0
// */

// 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'] ); 
} else {
  echo 'nodsfsd';
  // no route was matched
  header( $_SERVER["SERVER_PROTOCOL"] . ' 404 Not Found');
}
Exemplo n.º 22
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
Exemplo n.º 23
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'));
Exemplo n.º 24
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');
}
Exemplo n.º 25
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']) {
Exemplo n.º 26
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);
}
?>

Exemplo n.º 27
0
 /**
  * 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");
     }
 }
Exemplo n.º 28
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');
}
Exemplo n.º 29
-1
 public function addRoute($method, $route, $target, $name = null)
 {
     //Add the route as the default name, without the starting /
     if (!$name) {
         $name = mb_substr($route, 1);
     }
     $this->altoRouter->map($method, $route, $target, $name);
 }
Exemplo n.º 30
-1
 public function init()
 {
     $this->load->helper('url');
     if (!file_exists(APPPATH . '/config/database.php')) {
         redirect('install');
         exit;
     }
     session_start();
     //set the session userdata if non-existant
     if (!isset($_SESSION['userdata'])) {
         $_SESSION['userdata'] = [];
     }
     //set newFlashdata if non-existent
     if (!isset($_SESSION['newFlashdata'])) {
         $_SESSION['newFlashdata'] = [];
     }
     //empty out the "oldFlashdata" field
     $_SESSION['oldFlashdata'] = [];
     //shift newFlashdata over to oldFlashdata
     $_SESSION['oldFlashdata'] = $_SESSION['newFlashdata'];
     $_SESSION['newFlashdata'] = [];
     //module list
     $GLOBALS['modules'] = [];
     if (!file_exists(APPPATH . 'config/manifest.php')) {
         $this->load->helper('file');
         $manifest = "<?php defined('BASEPATH') OR exit('No direct script access allowed');\n//DO NOT EDIT THIS FILE\n\n";
         $this->classMap = [];
         $paths = [FCPATH . 'addons', APPPATH . 'modules', APPPATH . 'libraries', APPPATH . 'core'];
         $paymentModules = [];
         $shippingModules = [];
         $themeShortcodes = [];
         $routes = [];
         $modules = [];
         //just modules
         $moduleDirectories = [APPPATH . 'modules', FCPATH . 'addons'];
         foreach ($moduleDirectories as $moduleDirectory) {
             foreach (array_diff(scandir($moduleDirectory), ['..', '.']) as $availableModule) {
                 if (is_dir($moduleDirectory . '/' . $availableModule)) {
                     //create a codeigniter package path to the module.
                     //$this->load->add_package_path($moduleDirectory.'/'.$availableModule);
                     $modules[] = $moduleDirectory . '/' . $availableModule;
                 }
             }
         }
         foreach ($paths as $path) {
             $dir_iterator = new RecursiveDirectoryIterator($path);
             $iterator = new RecursiveIteratorIterator($dir_iterator, RecursiveIteratorIterator::SELF_FIRST);
             foreach ($iterator as $file) {
                 if (!is_dir($file)) {
                     $ext = pathinfo($file, PATHINFO_EXTENSION);
                     $filename = pathinfo($file, PATHINFO_FILENAME);
                     if ($ext == 'php') {
                         if ($filename == 'manifest') {
                             include $file;
                         }
                         $this->getPhpClasses((string) $file);
                     }
                 }
             }
         }
         $manifest .= '//ClassMap for autoloader' . "\n" . '$classes = ' . var_export($this->classMap, true) . ';';
         $manifest .= "\n\n" . '//Available Payment Modules' . "\n" . '$GLOBALS[\'paymentModules\'] =' . var_export($paymentModules, true) . ';';
         $manifest .= "\n\n" . '//Available Shipping Modules' . "\n" . '$GLOBALS[\'shippingModules\'] = ' . var_export($shippingModules, true) . ';';
         $manifest .= "\n\n" . '//Theme Shortcodes' . "\n" . '$GLOBALS[\'themeShortcodes\'] = ' . var_export($themeShortcodes, true) . ';';
         $manifest .= "\n\n" . '//Complete Module List' . "\n" . '$GLOBALS[\'modules\'] = ' . var_export($modules, true) . ';';
         $manifest .= "\n\n" . '//Defined Routes' . "\n" . '$routes = ' . var_export($routes, true) . ';';
         //generate the autoload file
         write_file(APPPATH . 'config/manifest.php', $manifest);
     }
     require APPPATH . 'config/manifest.php';
     //load in the database.
     $this->load->database();
     //set up routing...
     $router = new \AltoRouter();
     $base = trim($_SERVER['BASE'], '/');
     if ($base != '') {
         $router->setBasePath('/' . $base);
     }
     //set the homepage route
     $router->map('GET|POST', '/', 'GoCart\\Controller\\Page#homepage');
     //map the routes from the manifest.
     foreach ($routes as $route) {
         $router->map($route[0], $route[1], $route[2]);
     }
     foreach ($GLOBALS['modules'] as $module) {
         $this->load->add_package_path($module);
     }
     //autoloader for Modules
     spl_autoload_register(function ($class) use($classes) {
         if (isset($classes[$class])) {
             include $classes[$class];
         }
     });
     //autoload some libraries here.
     $this->load->model('Settings');
     $this->load->library(['session', 'auth', 'form_validation']);
     $this->load->helper(['file', 'string', 'html', 'language', 'form', 'formatting']);
     //get settings from the DB
     $settings = $this->Settings->get_settings('gocart');
     //loop through the settings and set them in the config library
     foreach ($settings as $key => $setting) {
         //special for the order status settings
         if ($key == 'order_statuses') {
             $setting = json_decode($setting, true);
         }
         //other config items get set directly to the config class
         $this->config->set_item($key, $setting);
     }
     date_default_timezone_set(config_item('timezone'));
     //if SSL is enabled in config force it here.
     if (config_item('ssl_support') && (!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] == 'off')) {
         $this->config->set_item('base_url', str_replace('http://', 'https://', config_item('base_url')));
         redirect(\CI::uri()->uri_string());
     }
     //do we have a dev username & password in place?
     //if there is a username and password for dev, require them
     if (config_item('stage_username') != '' && config_item('stage_password') != '') {
         if (!isset($_SERVER['PHP_AUTH_USER'])) {
             header('WWW-Authenticate: Basic realm="Login to restricted area"');
             header('HTTP/1.0 401 Unauthorized');
             echo config_item('company_name') . ' Restricted Location';
             exit;
         } else {
             if (config_item('stage_username') != $_SERVER['PHP_AUTH_USER'] || config_item('stage_password') != $_SERVER['PHP_AUTH_PW']) {
                 header('WWW-Authenticate: Basic realm="Login to restricted area"');
                 header('HTTP/1.0 401 Unauthorized');
                 echo 'Restricted Location';
                 exit;
             }
         }
     }
     // lets run the routes
     $match = $router->match();
     // call a closure
     if ($match && is_callable($match['target'])) {
         call_user_func_array($match['target'], $match['params']);
     } elseif ($match && is_string($match['target'])) {
         $target = explode('#', $match['target']);
         try {
             $class = new $target[0]();
             call_user_func_array([$class, $target[1]], $match['params']);
         } catch (Exception $e) {
             var_dump($e);
             throw_404();
         }
     } else {
         throw_404();
     }
 }