Example #1
0
<?php

// service initialization
require "Slim/Slim.php";
\Slim\Slim::registerAutoloader();
require "../config.php";
require "../helpers.php";
$db = @new mysqli($db_address, $db_username, $db_password, $db_database);
if ($db->connect_errno != 0) {
    die("Connection to database failed: " . $db->connect_error);
}
// assign routes
$app = new \Slim\Slim();
$app->contentType("application/json");
$app->hook("slim.after", function () {
    global $db;
    $db->close();
});
$app->get("/user/:id", "GetUser");
$app->post("/user", "CreateUser");
$app->get("/layout", "GetAllLayouts");
$app->post("/layout", "SaveLayout");
$app->get("/layout/:id", "GetLayout");
$app->delete("/layout/:id", "DeleteLayout");
$app->run();
// helpers
class IksdehException extends Exception
{
    function __construct($code = 400, $message = "")
    {
        parent::__construct($message, $code);
    }
Example #2
0
 /**
  * Test clear hooks
  *
  * Pre-conditions:
  * Slim app instantiated;
  * Two hooks exist, each with one listener;
  *
  * Post-conditions:
  * Case A: Listeners for 'test.hook.one' are cleared;
  * Case B: Listeners for all hooks are cleared;
  */
 public function testHookClear()
 {
     $app = new \Slim\Slim();
     $app->hook('test.hook.one', function () {
     });
     $app->hook('test.hook.two', function () {
     });
     $app->clearHooks('test.hook.two');
     $this->assertEquals(array(array()), $app->getHooks('test.hook.two'));
     $hookOne = $app->getHooks('test.hook.one');
     $this->assertTrue(count($hookOne[10]) === 1);
     $app->clearHooks();
     $this->assertEquals(array(array()), $app->getHooks('test.hook.one'));
 }
Example #3
0
$app->hook('slim.before.router', function () use($app) {
    $uri = $app->request()->getResourceUri();
    if (($k = strpos($uri, "/", 1)) === false) {
        $controller = $uri;
    } else {
        $controller = '/' . strtok($uri, '/');
        $controller .= '/' . strtok('/');
    }
    switch ($controller) {
        case "/sapi/configs":
            require_once BASE_PATH . "/routes/configs.route.php";
            break;
        case "/sapi/consumer":
            require_once BASE_PATH . "/routes/consumer.route.php";
            break;
        case "/sapi/commands":
        case "/sapi/command":
            require_once BASE_PATH . "/routes/command.route.php";
            break;
        case "/sapi/contacts":
        case "/sapi/contact":
            require_once BASE_PATH . "/routes/contact.route.php";
            break;
        case "/sapi/contactgroups":
        case "/sapi/contactgroup":
            require_once BASE_PATH . "/routes/contactgroup.route.php";
            break;
        case "/sapi/contacttemplates":
        case "/sapi/contacttemplate":
            require_once BASE_PATH . "/routes/contacttemplate.route.php";
            break;
        case "/sapi/deployment":
            require_once BASE_PATH . "/routes/deployment.route.php";
            break;
        case "/sapi/event":
            require_once BASE_PATH . "/routes/event.route.php";
            break;
        case "/sapi/hostgroups":
        case "/sapi/hostgroup":
            require_once BASE_PATH . "/routes/hostgroup.route.php";
            break;
        case "/sapi/hosttemplates":
        case "/sapi/hosttemplate":
            require_once BASE_PATH . "/routes/hosttemplate.route.php";
            break;
        case "/sapi/matrix":
            require_once BASE_PATH . "/routes/matrix.route.php";
            break;
        case "/sapi/nagiospluginsmeta":
        case "/sapi/nagiosplugins":
        case "/sapi/nagiosplugin":
            require_once BASE_PATH . "/routes/nagiosplugin.route.php";
            break;
        case "/sapi/nrpecfg":
            require_once BASE_PATH . "/routes/nrpecfg.route.php";
            break;
        case "/sapi/nrpecmds":
        case "/sapi/nrpecmd":
            require_once BASE_PATH . "/routes/nrpecmd.route.php";
            break;
        case "/sapi/nrpepluginsmeta":
        case "/sapi/nrpeplugins":
        case "/sapi/nrpeplugin":
            require_once BASE_PATH . "/routes/nrpeplugin.route.php";
            break;
        case "/sapi/supnrpecfg":
            require_once BASE_PATH . "/routes/supnrpecfg.route.php";
            break;
        case "/sapi/supnrpepluginsmeta":
        case "/sapi/supnrpeplugins":
        case "/sapi/supnrpeplugin":
            require_once BASE_PATH . "/routes/supnrpeplugin.route.php";
            break;
        case "/sapi/services":
        case "/sapi/service":
            require_once BASE_PATH . "/routes/service.route.php";
            break;
        case "/sapi/servicedependencies":
        case "/sapi/servicedependency":
            require_once BASE_PATH . "/routes/servicedependency.route.php";
            break;
        case "/sapi/serviceescalations":
        case "/sapi/serviceescalation":
            require_once BASE_PATH . "/routes/serviceescalation.route.php";
            break;
        case "/sapi/servicegroups":
        case "/sapi/servicegroup":
            require_once BASE_PATH . "/routes/servicegroup.route.php";
            break;
        case "/sapi/servicetemplates":
        case "/sapi/servicetemplate":
            require_once BASE_PATH . "/routes/servicetemplate.route.php";
            break;
        case "/sapi/timeperiodsmeta":
        case "/sapi/timeperiods":
        case "/sapi/timeperiod":
            require_once BASE_PATH . "/routes/timeperiod.route.php";
            break;
        case "/api/getMGCfg":
        case "/api/getNagiosCfg":
        case "/api/getNRPECfg":
        case "/api/getSupNRPECfg":
        case "/api/getNRPEPlugin":
        case "/api/getSupNRPEPlugin":
        case "/api/getRouterVM":
        case "/api/getNagiosPlugin":
        case "/api/getNagiosPlugins":
            require_once BASE_PATH . "/routes/apiv1.route.php";
            break;
        default:
            break;
    }
});
Example #4
0
});
// 只在“development”模式中执行
$app->configureMode('development', function () use($app) {
    $app->config(array('log.enable' => false, 'debug' => true));
});
//使用 \Slim\Middleware\SessionCookie 中间件把会话数据储存到经过加密和散列的 HTTP cookies中
$app->add(new \Slim\Middleware\SessionCookie(array('expires' => '20 minutes', 'path' => '/', 'domain' => DOMAIN, 'secure' => false, 'httponly' => true, 'name' => 'data_session', 'secret' => 'CHANGE_ME', 'cipher' => MCRYPT_RIJNDAEL_256, 'cipher_mode' => MCRYPT_MODE_CBC)));
//权限判断
$app->hook('slim.before.dispatch', function () use($app) {
    $req = $app->request();
    // 将POST的UTCC的放行,在逻辑中检查是否合理
    if (strpos($_SERVER['REQUEST_URI'], 'utcc') > 0) {
        return true;
    }
    if (strpos($_SERVER['REQUEST_URI'], 'test') !== FALSE) {
        return true;
    }
    if (isset($_SESSION['username']) && $_SESSION['username'] == $req->params('username') && isset($_SESSION['token']) && $_SESSION['token'] == $req->params('token') && isset($_SESSION['url']) && in_array(substr($req->getPath(), strlen(API_PREFIX)), $_SESSION['url'])) {
        return true;
    }
    //wrong parameter error
    $err_res = json_encode(['meta' => ['status' => 401, 'msg' => 'you are not permitted to access this interface. wrong parameter']]);
    $app->halt(401, $err_res);
});
//单例mysql
$db_config = (require_once CODE_BASE . 'configs/mysql.php');
$app->container->singleton('db_ku6_report', function () use($db_config) {
    return new Mysql($db_config['ku6_report']);
});
$app->container->singleton('db_new_utcc', function () use($db_config) {
    return new Mysql($db_config['new_utcc']);
});
Example #5
0
R::setup('mysql:host=' . DB_HOST . ';dbname=' . DB_NAME, DB_USERNAME, DB_PASSWORD);
R::freeze(DB_FREEZE);
// Slim app instance
$app = new \Slim\Slim(['view' => new EnhancedView()]);
// Slim Config
$app->config(['templates.path' => 'app/views', 'debug' => APP_DEBUG]);
// Add support for JSON posts
$app->add(new \Slim\Middleware\ContentTypes());
// JSON view function
function APIrequest()
{
    $app = \Slim\Slim::getInstance();
    $app->view(new \JsonView());
    $app->view->clear();
}
// Set webroot for portable
$app->hook('slim.before', function () use($app) {
    $app->wroot = $app->request->getUrl() . $app->request->getRootUri();
    $app->view()->appendData(['wroot' => $app->wroot]);
});
// Load routes
$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator(dirname(__FILE__) . '/routes/'));
foreach ($iterator as $file) {
    $fname = $file->getFilename();
    if (preg_match('%\\.php$%', $fname)) {
        require $file->getPathname();
    }
}
// Errors
require 'sys/errors.php';
$app->run();
Example #6
0
            $app->redirect($env['rootUri'] . 'login');
        } else {
            if ($role == 'admin') {
                if ($_SESSION['role'] != 'admin') {
                    $app->flash('danger', 'Necesitas iniciar sesion como administrador.');
                    $app->redirect($env['rootUri']);
                }
            }
        }
    };
};
//crea variable $user y se la agrega a todos los views para facil deteccion de sesiones
$app->hook('slim.before.dispatch', function () use($app) {
    $user = array();
    if (isset($_SESSION['user'])) {
        $user['email'] = $_SESSION['user'];
        $user['nombre'] = $_SESSION['nombre'];
    }
    $app->view()->setData('user', $user);
});
/*
 * SET some globally available view data
 */
$resourceUri = $_SERVER['REQUEST_URI'];
//Uri del sitio desde el root del dominio
$rootUri = '/';
//Uri de los contenidos publicos
$assetUri = $rootUri . 'web/';
$env = $app->environment();
$env['rootUri'] = $rootUri;
$app->view()->appendData(array('app' => $app, 'rootUri' => $rootUri, 'assetUri' => $assetUri, 'resourceUri' => $resourceUri));
foreach (glob(ROOT . 'app/controllers/*.php') as $router) {
Example #7
0
            print_r($doc);
        }
        $mongoCollection = getMongoCollection('tag');
        $result = $mongoCollection->find();
        foreach ($result as $doc) {
            echo print_r($doc);
        }
    });
} else {
    //本番
    error_reporting(E_ALL ^ E_NOTICE ^ E_DEPRECATED);
    ini_set('display_errors', 0);
}
$app->hook('slim.before', function () use($app) {
    $app->response->headers->set('Cache-Control', 'private, no-store, no-cache, must-revalidate');
    $app->response->headers->set('Pragma', 'no-cache');
    $app->view->appendData(array('product_path' => $app->config('product_path'), 'static_path' => $app->config('static_path')));
});
//------------------------------------------------------------------------------------
// ルーティング + コントローラー
//------------------------------------------------------------------------------------
$app->group(rtrim($app->config('product_path'), '/'), function () use($app) {
    $app->get('/', function () use($app) {
        unset($_SESSION['project']);
        unset($_SESSION['sheetData']);
        //connect to mongo
        $mongoCollection = getMongoCollection('project');
        $get = $app->request->get();
        //list
        $list['creator'] = $mongoCollection->distinct('dct:creator');
        $list['tag'] = $mongoCollection->distinct('eg:tag');
Example #8
0
if ($config['mode'] === 'development') {
    ini_set('display_errors', true);
    error_reporting(1);
}
// path to save logs to
$logWriter = new \Slim\LogWriter(fopen($config['log_path'] . 'applog.log', 'a+'));
// instantiate slim framework
$options = array('debug' => $config['debug'], 'templates.path' => 'views/', 'mode' => $config['mode'], 'log.writer' => $logWriter, 'cookies.encrypt' => true, 'cookies.cipher' => MCRYPT_RIJNDAEL_256, 'cookies.secret_key' => md5('@!secret!@'), 'cookies.lifetime' => '20 minutes');
$app = new \Slim\Slim($options);
$app->setName($config['appname']);
// later in view for example: $app->getName()
$app->hook('slim.before.router', function () use($app, $config) {
    $setting = new \BloggerCMS\Setting();
    $app->view()->setData('app', $app);
    // we can now use $app in views
    $app->view()->setData('root', ltrim(dirname($_SERVER['SCRIPT_NAME']), '\\'));
    $app->view()->setData('layoutsDir', dirname(__FILE__) . '/layouts/');
    $app->view()->setData('dateFormat', $config['dateFormat']);
    $app->view()->setData('blogURL', $setting->getBlogURL());
});
// slim environment
$environment = \Slim\Environment::getInstance();
// logging
$log = $app->getLog();
$log->setEnabled(false);
if ($config['mode'] === 'development') {
    $app->configureMode('development', function () use($log) {
        /*
        $log->setLevel(\Slim\Log::DEBUG);
        $log->setEnabled(true);
        $log->debug("Application Started...");
Example #9
0
<?php

session_cache_limiter(false);
session_start();
date_default_timezone_set('Europe/Paris');
define('APP_PATH', __DIR__ . '/..');
define('CONFIG_PATH', __DIR__);
define('ROUTES_PATH', APP_PATH . '/routes');
define('LIB_PATH', APP_PATH . '/lib');
define('MODELS_PATH', APP_PATH . '/models');
define('WEBROOT_PATH', __DIR__ . '/../../public');
require CONFIG_PATH . '/app.php';
require CONFIG_PATH . '/secrets.php';
if (!defined('PROD')) {
    define('PROD', !empty($_SERVER['SERVER_NAME']) && strpos($_SERVER['SERVER_NAME'], APP_SERVER) !== false);
}
error_reporting(PROD ? 0 : E_ALL);
require APP_PATH . '/vendor/autoload.php';
require LIB_PATH . '/PlatesView.php';
$view = new PlatesView();
$app = new \Slim\Slim(array('view' => $view, 'templates.path' => APP_PATH . '/views', 'debug' => intval(!PROD), 'mode' => PROD ? 'production' : 'development'));
define('HOST', $app->request()->getUrl());
define('CURRENT', $app->request()->getPath());
$app->hook('slim.before.dispatch', function () use($app) {
    $app->view()->setData('app', $app);
});
Example #10
0
<?php

require_once 'vendor/autoload.php';
require 'redbean/rb-p533.php';
$conn = parse_ini_file('config/config.ini');
// Connect to database with Redbean
R::setup('mysql:host=' . $conn['host'] . ';dbname=' . $conn['dbname'], $conn['username'], $conn['password']);
// Initialize our Slim app
$app = new \Slim\Slim(array('view' => new \Slim\Views\Twig(), 'templates.path' => 'views/'));
$app->baseRoute = '/slimredtwig' . '/';
$app->hook('slim.before.dispatch', function () use($app) {
    // Site details
    $siteTitle = 'Slim Red Twig App';
    // Build the navigation
    $nav1 = array('name' => 'Home', 'route' => $app->baseRoute);
    $nav2 = array('name' => 'Books', 'route' => $app->baseRoute . 'books');
    $nav3 = array('name' => 'Posts', 'route' => $app->baseRoute . 'posts');
    $menu = array($nav1, $nav2, $nav3);
    $app->view()->setData(array('menu' => $menu, 'title' => $siteTitle));
});
// App routes ----------------------------------------------
$app->get('/', function () use($app) {
    $app->render('home.php');
});
$app->get('/hello/:name', function ($name) use($app) {
    $app->render('test.php', array('name' => $name));
});
$app->get('/books', function () use($app) {
    // Grab all the books
    $books = R::findAll('book');
    $app->render('books.php', array('books' => $books));
Example #11
0
\Slim\Slim::registerAutoloader();
require_once '../package/Package.php';
\Package\Package::registerAutoloader();
$app = new \Slim\Slim(array('debug' => true, 'templates.path' => '../application/view/'));
require_once '../application/controller/index.php';
require_once '../application/controller/error.php';
$app->hook('slim.before.router', function () use($app) {
    $uri = substr(preg_replace('/(\\/+)/', '/', $app->request->getResourceUri()), 1);
    $pieces = explode('/', $uri);
    $basePath = $path = realpath('../application/controller') . '/';
    foreach ($pieces as $value) {
        $value = trim($value);
        if ($value !== '' && file_exists($path . $value) && is_dir($path . $value)) {
            $path = $path . $value . '/';
            if (file_exists($path . 'index.php') && is_file($path . 'index.php') && strpos(realpath($path . 'index.php'), $basePath) === 0) {
                require_once realpath($path . 'index.php');
            }
        } else {
            break;
        }
    }
    if (file_exists($path . $value . '.php') && is_file($path . $value . '.php') && strpos(realpath($path . $value . '.php'), $basePath) === 0) {
        require_once realpath($path . $value . '.php');
    }
});
$filesList = scandir('../config');
foreach ($filesList as $fileName) {
    if (substr($fileName, -11) == '.config.php') {
        $key = substr($fileName, 0, -11);
        $value = (include '../config/' . $fileName);
        $app->config($key, $value);
require 'vendor/autoload.php';
$app = new \Slim\Slim();
$app->add(new \Slim\Middleware\SessionCookie(array('secret' => 'myappsecret')));
$authenticate = function ($app) {
    return function () use($app) {
        if (!isset($_SESSION['user'])) {
            $_SESSION['urlRedirect'] = $app->request()->getPathInfo();
            $app->flash('error', 'Login required');
            $app->redirect('/login');
        }
    };
};
$app->hook('slim.before.dispatch', function () use($app) {
    $user = null;
    if (isset($_SESSION['user'])) {
        $user = $_SESSION['user'];
    }
    $app->view()->setData('user', $user);
});
$app->get("/", function () use($app) {
    $app->render('index.php');
});
$app->get("/about", function () use($app) {
    $app->render('about.php');
});
$app->get("/level/contact", function () use($app) {
    $app->render('levelContact.php');
});
$app->get("/logout", function () use($app) {
    unset($_SESSION['user']);
    $app->view()->setData('user', null);
Example #13
0
// PARIS (MODELS)
// $models = glob("../app/models/*.php");
// foreach ($models as $filename) {
//     include $filename;
// }
// IDIORM (ORM)
ORM::configure($config['database']['dsn']);
ORM::configure('username', $config['database']['username']);
ORM::configure('password', $config['database']['password']);
// tell server to expect utf-8 encoded characters
// you can also achieve the same by addind ";charset=utf8" to your dsn
// http://stackoverflow.com/questions/1650591/whether-to-use-set-names
ORM::configure('driver_options', array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'));
// This hook runs before every request
$app->hook('slim.before.dispatch', function () use($app, $config) {
    $app->view()->setData('config', $config);
});
// FACEBOOK AUTHENTICATION
$auth = function ($app, $config) {
    return function () use($app, $config) {
        // if localhost, bypass authentication
        if ($config['general']['env'] === 'local') {
            return true;
        }
        // fix for third party cookies (Safari)
        if (!isset($_REQUEST['signed_request']) && !isset($_COOKIE['cookie_fix'])) {
            exit("<script>window.top.location='" . $config['general']['base_url'] . DS . 'cookies_fix' . "'</script>");
        }
        $fb_scope = $config['facebook']['scope'];
        $canvas_page = $config['facebook']['canvas_page'];
        $user_id = $app->facebook->getUser();
Example #14
0
<?php

require 'vendor\\autoload.php';
require 'RedBean\\rb.php';
require 'functions.php';
session_start();
$app = new \Slim\Slim();
$view = $app->view();
$view->setTemplatesDirectory("./templates");
$app->add(new \Slim\Middleware\SessionCookie(array('secret' => '1224329633')));
$app->hook('slim.before', function () use($app) {
    $app->view()->appendData(array('baseUrl' => '/backoffice'));
});
$authenticate = function ($app) {
    return function () use($app) {
        // Gets the md5 version of the username and password in the database
        $configs = parse_ini_file('config.ini');
        $system_username = $configs['username'];
        $system_password = $configs['password'];
        $hashed_system_session = md5($system_username . $system_password);
        // If there is no session user variable
        if (!isset($_SESSION['user'])) {
            $_SESSION['urlRedirect'] = $app->request()->getPathInfo();
            $app->flash('error', 'Login required');
            $app->redirect('/backoffice/login');
        }
        // if the user session variable value does not corresponde to the one in the configs
        if ($_SESSION['user'] != $hashed_system_session) {
            $_SESSION['urlRedirect'] = $app->request()->getPathInfo();
            $app->flash('error', 'Login required');
            $app->redirect('/backoffice/login');
 public static function dispatcher()
 {
     header('Access-Control-Allow-Origin: *');
     header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
     header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');
     error_reporting(E_ALL ^ E_NOTICE ^ E_WARNING ^ E_STRICT);
     $app = new \Slim\Slim();
     \Slim\Slim::registerAutoloader();
     $app->contentType('application/json; charset=utf-8');
     $app->config('debug', true);
     //        echo "<pre>";
     if (WP_DEBUG) {
         $root = strtolower($app->request()->getRootUri()) . '/api';
     } else {
         $root = "/api";
     }
     //        var_dump($root);
     //            $root = "/api";
     //            $root = strtolower($app->request()->getRootUri()) . '/api';
     //        else
     //        $root = "/api";
     //        var_dump($root);
     //        $root = null;
     //        $root = var_dump($app->request()->getRootUri());
     //        die();
     //        });
     //        var_dump($app->request->headers);
     $app->hook('slim.before.dispatch', function () use($app) {
         // Conferir se é url que exige autenticação
         $req = $_SERVER['REQUEST_URI'];
         if (strpos($req, '/autenticar/') !== false) {
             return;
         }
         $headers = self::request_headers();
         //            var_dump($headers);die();
         $app = \Slim\Slim::getInstance();
         $erro = null;
         $api_user_id = $headers['X-API-USER-ID'];
         $api_token = $headers['X-API-TOKEN'];
         if ($api_user_id == null || $api_token == null) {
             $erro = "É preciso informar X-API-USER-ID e X-API-TOKEN no header.";
         } else {
             // Sanitizar user_id
             /* @var $pessoa Pessoa */
             $pessoa = Pessoas::getInstance()->getById($api_user_id);
             // Sanitizar token
             if ($pessoa == null) {
                 $erro = 'Não te encontramos em nossa base de dados...';
             } else {
                 if (md5($pessoa->id . '_' . $pessoa->password) != $api_token) {
                     $erro = 'Password inválido';
                 }
             }
         }
         if ($erro) {
             $app->response->headers['X-Authenticated'] = 'False';
             $app->halt('401', '{"error":{"text": "' . $erro . '" }}');
         }
     });
     $app->group($root, function () use($app) {
         // '/'
         $app->get('/', function () use($app) {
             echo json_encode(array("bem vindo", "a API"));
         });
         // Autenticate
         $app->post('/autenticar/', function () use($app) {
             // Obter pessoa, e usuário
             $email = $_POST['email'];
             $password = $_POST['password'];
             if ($email == '' || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
                 echo json_encode(array('Erro' => 'Informe um endereço de email válido.'));
                 return;
             }
             /* @var $pessoa Pessoa */
             $pessoa = Pessoas::getInstance()->getByEmail($email);
             if ($pessoa == null) {
                 echo json_encode(array('Erro' => 'Não te encontramos em nossa base de dados...'));
                 return;
             }
             // Validar senha, antes de mais nada
             // @TODO Buscar user do wordpress que seja esta pessoa e verificar se está ativo, senão, é pessoa normal
             // Aqui, só pode ser um participante do grupo ou inscrito em algum evento
             $nPessoa = ControllerApi::decoratePessoa($pessoa);
             $return = array('pessoa' => $nPessoa);
             $return = PLib::object_to_array($return);
             //                    $return = PLib::array_utf8_encode($return);
             echo json_encode($return, JSON_NUMERIC_CHECK);
             return;
         });
         $app->group('/gamification', function () use($app) {
             $app->get('/ranking', function () use($app) {
                 $ranking = Gamification::getInstance()->getUsersPointsRanking(300);
                 //                    var_dump($ranking);
                 $nRanking = ControllerApi::decorateRanking($ranking);
                 echo json_encode($nRanking);
             });
             $app->get('/user/:id', function ($id) use($app) {
                 $pessoa = ControllerApi::getPessoa($id, true);
                 if ($pessoa) {
                     /* @var $gamification Gamification */
                     $gamification = Gamification::getInstance();
                     $gamification->setUserId($id);
                     $nPessoa = ControllerApi::decorateUserGamification($pessoa);
                     $badges = $gamification->getBadges();
                     $nBadges = ControllerApi::decorateBadges($badges);
                     $return = array('user' => $nPessoa, 'badge' => $nBadges);
                     $return = PLib::object_to_array($return);
                     echo json_encode($return, JSON_NUMERIC_CHECK);
                 }
             });
         });
         // '/'
         $app->get('/notificacao/', function () use($app) {
             die("notificação");
         });
         // Retorna uma inscrição
         $app->get('/inscricao/:idInscricao/simples/', function ($idInscricao) use($app) {
             if (strlen($idInscricao) > 10) {
                 $transactionId = $idInscricao;
                 $inscricao = Inscricoes::getInstance()->callbackPagamento(1, $transactionId);
                 if (get_class($inscricao) != 'Inscricao') {
                     $erro = 'Transação não identificada..';
                 }
             } else {
                 /* @var $inscricao Inscricao */
                 $inscricao = Inscricoes::getInstance()->getById($idInscricao);
                 if ($inscricao == null) {
                     $erro = 'Inscrição não localizada (' . $idInscricao . ')';
                 }
             }
             if ($erro) {
                 echo json_encode(array('erro' => $erro));
             } else {
                 if ($erro == null) {
                     if ($inscricao->confirmado == true) {
                         $mensagem = "wizard_fim_pagamento_confirmado";
                     } else {
                         $mensagem = "wizard_fim_pagamento_aguardando_confirmacao";
                     }
                     $mensagem = Mensagens::getInstance()->get($mensagem, $inscricao->evento(), $inscricao->pessoa(), $inscricao, true);
                     $nInscricao = array('confirmado' => $inscricao->confirmado, 'mensagem' => $mensagem);
                     $return = array('inscricao' => $nInscricao);
                     $nInscrito = PLib::object_to_array($return);
                     echo json_encode($nInscrito, JSON_NUMERIC_CHECK);
                 }
             }
         });
         // Redireciona para URL de pagamento no gateway - Por enquanto só funciona pro devfest
         $app->get('/inscricao/:idInscricao/pagar/', function ($idInscricao) use($app) {
             /* @var $inscricao Inscricao */
             $inscricao = Inscricoes::getInstance()->getById($idInscricao);
             if ($inscricao == null) {
                 echo json_encode(array('erro' => 'Inscrição não localizada (' . $idInscricao . ')'));
                 return;
             }
             $urlRetorno = BASE_URL . '/confirmacao?ticket=' . $inscricao->id * 333;
             $url = \lib\PagSeguroUtil::getUrlPagamento($inscricao, $urlRetorno);
             $return = array('url' => $url);
             $return = PLib::object_to_array($return);
             echo json_encode($return, JSON_NUMERIC_CHECK);
         });
         // Retorna dados de uma pessoa
         $app->get('/pessoa/:idPessoa/', function ($idPessoa) use($app) {
             $pessoa = ControllerApi::getPessoa($idPessoa, true);
             if ($pessoa) {
                 $nPessoa = ControllerApi::decoratePessoa($pessoa);
                 $return = array('pessoa' => $nPessoa);
                 //                $return = PLib::array_utf8_encode($return);
                 $return = PLib::object_to_array($return);
                 echo json_encode($return, JSON_NUMERIC_CHECK);
             }
         });
         // Retorna as inscrições de uma pessoa
         $app->get('/pessoa/:idPessoa/inscricoes/', function ($idPessoa) use($app) {
             $pessoa = ControllerApi::getPessoa($idPessoa, true);
             if ($pessoa) {
                 // Obter inscrições da pessoa
                 $inscricoes = Inscricoes::getInstance()->getByPessoa($pessoa->id);
                 $nInscricoes = array();
                 if ($inscricoes == null) {
                     echo json_encode(array('mensagem' => 'Sem inscrições desta pessoa'));
                     return;
                 }
                 foreach ($inscricoes as $inscricao) {
                     $nInscricoes[] = ControllerApi::decorateInscricaoTeceiros($inscricao);
                 }
                 $return = array('inscricoes' => $nInscricoes);
                 $return = PLib::object_to_array($return);
                 echo json_encode($return, JSON_NUMERIC_CHECK);
             }
         });
         // Realiza uma inscrição
         $app->post('/inscrever/:idEvento/', function ($idEvento) use($app) {
             $idPessoa = $_POST['id_pessoa'];
             $nome = trim(ucfirst($_POST['nome']));
             $email = trim(strtolower($_POST['email']));
             $cpf = trim($_POST['cpf']);
             $celular = PLib::only_numbers($_POST['celular']);
             if (strpos($celular, '55') === 0) {
                 $celular = substr($celular, 2);
             }
             /* @var $evento Evento */
             $evento = Eventos::getInstance()->getById($idEvento);
             if ($evento == null) {
                 echo json_encode(array('erro' => 'Evento não localizado na base de dados (' . $idEvento . ')'));
                 return;
             }
             $validacao = PLib::coalesce($evento->validacao_pessoa, 'email');
             if ($idPessoa == null && ($nome == null || $celular == null || $email == null || ${$validacao} == null)) {
                 echo json_encode(array('erro' => 'Envie todos os dados (' . $nome . $email . $celular . ').' . print_r($_POST, true)));
                 return;
             }
             if ($idPessoa == null && !filter_var($email, FILTER_VALIDATE_EMAIL)) {
                 echo json_encode(array('erro' => 'Email inválido'));
                 return;
             }
             if ($idPessoa == null && strlen($celular) < 8) {
                 echo json_encode(array('erro' => 'Celular inválido'));
                 return;
             }
             // Mesmo sem id de pessoa, tentar encontrar pessoa por email
             if ($idPessoa == null) {
                 $pessoa = Pessoas::getInstance()->getByMd5($email);
                 if ($pessoa != null) {
                     $idPessoa = $pessoa->id;
                 }
             }
             //                $validacao='cpf';
             //                if ($validacao=='cpf' && $cpf!=null && !PLib::validade_cpf($cpf)){
             //                    echo json_encode(array('erro' => 'CPF inválido ('.$cpf.')'));
             //                    return;
             //                }
             // Incluir pessoa
             /* @var $pessoa Pessoa */
             if ($idPessoa == null) {
                 /* @var $pessoa Pessoa */
                 $pessoa = new Pessoa();
                 $pessoa->nome = $nome;
                 $pessoa->email = $email;
                 $pessoa->celular = $celular;
                 if ($validacao == 'cpf') {
                     $pessoa->cpf = PLib::str_mask(PLib::only_numbers($cpf), '###.###.###-##');
                 }
                 //                    PLib::var_dump($pessoa);
                 $pessoa = Pessoas::getInstance()->insert($pessoa);
             } else {
                 $pessoa = Pessoas::getInstance()->getById($idPessoa);
                 if ($nome != null && strlen($nome) > 2) {
                     $pessoa->nome = $nome;
                 }
                 if ($celular != null && strlen($celular) > 2) {
                     $pessoa->celular = $celular;
                 }
                 $pessoa->save();
             }
             // Extras? Pegar do post.... xeu pensar - ter como limitar e tal.. como tornar mais seguro?
             $extras = array();
             foreach ($_POST as $key => $value) {
                 if ($key == 'id_pessoa' || $key == 'nome' || $key == 'cpf' || $key == 'celular' || $key == 'email') {
                     continue;
                 }
                 $extra = array('titulo' => $key, 'valor' => $value);
                 $extras[$key] = $extra;
             }
             if (count($extras) > 0) {
                 $pessoa->setExtras($extras);
                 $pessoa->save();
             }
             //PLib::var_dump($pessoa->getExtrasArray());
             //PLib::var_dump($pessoa);die();
             $idPessoa = $pessoa->id;
             // Verificar se já está inscrita.... hum, tem algumas situações aqui
             $inscricao = Inscricoes::getInstance()->getByEventoPessoaConfirmado($idEvento, $idPessoa);
             if ($inscricao != null) {
                 echo json_encode(array('erro' => "Você já está inscrito e confirmado para este evento!"));
                 return;
             }
             // Já salvar registro de inscrição
             $inscricao = Inscricoes::getInstance()->certificarInscricao($evento, $pessoa, $evento->confirmacao == "preinscricao");
             $nInscrito = ControllerApi::decorateInscricao($inscricao);
             $return = array('inscricao' => $nInscrito);
             $return = PLib::object_to_array($return);
             echo json_encode($return, JSON_NUMERIC_CHECK);
         });
         // Return "current" events
         $app->get('/eventos/', function () use($app) {
             $eventos = Eventos::getInstance()->getAll();
             if ($eventos == null) {
                 echo json_encode(array('erro' => 'Nenhum evento registrado....'));
                 return;
             }
             $events = array();
             /* @var $evento Evento */
             foreach ($eventos as $evento) {
                 if ($evento->preInscricao()) {
                     continue;
                 }
                 $nEvento = ControllerApi::decorateEvento($evento, false);
                 $events[] = $nEvento;
             }
             $events = PLib::object_to_array($events);
             echo json_encode($events, JSON_NUMERIC_CHECK);
         });
         // Return "current" events
         $app->get('/eventos/futuros/', function () use($app) {
             $eventos = Eventos::getInstance()->getAcontecendoFuturos();
             if ($eventos) {
                 $events = array();
                 /* @var $evento Evento */
                 foreach ($eventos as $evento) {
                     $nEvento = ControllerApi::decorateEvento($evento, false);
                     $events[] = $nEvento;
                 }
                 $events = PLib::object_to_array($events);
                 echo json_encode($events, JSON_NUMERIC_CHECK);
             }
         });
         // Return "current" events
         $app->get('/eventos/atual/', function () use($app) {
             $evento = ControllerApi::getEventoAtual();
             if ($evento == null) {
                 echo json_encode(array('erro' => 'Não existe um evento atual'));
                 return;
             }
             $evento = ControllerApi::decorateEvento($evento, false);
             $events = PLib::object_to_array($evento);
             echo json_encode($events, JSON_NUMERIC_CHECK);
         });
         // Return "current" events
         $app->get('/eventos/terceiros/', function () use($app) {
             // Obter eventos de outros sites de eventos
             //                $sites = array(
             //                );
             //                $eventosArray = array();
             //                foreach ($sites as $site) {
             //                    //  Initiate curl
             //                    $ch = curl_init();
             //                    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
             //                    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
             //                    curl_setopt($ch, CURLOPT_URL, $site . '/api/eventos/futuros/');
             //                    $result = curl_exec($ch);
             //                    curl_close($ch);
             ////                    var_dump($result);
             //                    if ($result) {
             //                        $eventosJson = json_decode($result, true);
             ////                        var_dump($eventosJson);
             //                        if ($eventosJson) {
             //                            foreach ($eventosJson as $evento) {
             ////                                $evento = Eventos::getInstance()->populate($evento);
             //                                $eventosArray[] = $evento;
             //                            }
             //                        } else {
             //                            echo "nune " . $site;
             //                        }
             //                    } else {
             ////                        echo "none ".$site;
             //                    }
             //                }
             //                // Ordernar
             ////                var_dump($eventosArray);
             //                usort($eventosArray, 'ControllerApi::ordem');
             ////                Eventos::getInstance()->ordenar($eventosArray,true);
             ////                $eventosReturn=array();
             ////                foreach($eventosArray as $evento) {
             ////                    $eventosReturn[]= ControllerApi::decorateEvento($evento, false);
             ////                }
             //
             //                $eventosReturn = PLib::object_to_array($eventosArray);
             //                echo json_encode($eventosReturn, JSON_NUMERIC_CHECK);
         });
         // Retorna um evento e seus dados
         $app->get('/evento/:idEvento/', function ($idEvento) use($app) {
             $evento = Eventos::getInstance()->getById($idEvento);
             if ($evento == null) {
                 echo json_encode(array('erro' => 'Evento não localizado na base de dados (' . $idEvento . ')'));
                 return;
             }
             $nEvento = ControllerApi::decorateEvento($evento, true);
             $events = PLib::object_to_array($nEvento);
             echo json_encode($events, JSON_NUMERIC_CHECK);
         });
         // Retorna os inscritos no evento
         $app->get('/inscritos/:idEvento/', function ($idEvento) use($app) {
             $inscritos = Inscricoes::getInstance()->getByEvento($idEvento, null, "ev_pessoas.nome");
             //                var_dump($inscritos);
             $registrations = array();
             /* @var $inscrito Inscricao */
             foreach ($inscritos as $inscrito) {
                 $nInscrito = ControllerApi::decorateInscricao($inscrito);
                 $registrations[] = $nInscrito;
             }
             $registrations = PLib::object_to_array($registrations);
             echo json_encode($registrations, JSON_NUMERIC_CHECK);
         });
         // Dá presença a um inscrito
         $app->post('/inscricao/self_chekin/', function () use($app) {
             /* @var $inscricao Inscricao */
             $inscricao = null;
             $identificacao = $_POST['identificacao'];
             // email - ou id_evento-id_inscricao-id_pessoa
             if (substr_count($identificacao, '-') === 2) {
                 $id_evento = substr($identificacao, 0, strpos($identificacao, '-'));
                 $id_inscricao = substr($identificacao, strpos($identificacao, '-') + 1);
                 $id_pessoa = substr($id_inscricao, strpos($identificacao, '-') + 1);
                 $id_inscricao = substr($id_inscricao, 0, strpos($identificacao, '-'));
                 //                    var_dump($id_evento);
                 //                    var_dump($id_inscricao);
                 //                    var_dump($id_pessoa);
                 $inscricao = Inscricoes::getInstance()->getById($id_inscricao);
                 if ($inscricao == null) {
                     echo json_encode(array('erro' => 'Inscrição não localizada...'));
                     return;
                 } else {
                     if ($inscricao->id_pessoa != $id_pessoa) {
                         echo json_encode(array('erro' => 'As informações não batem! Inscrição X Pessoa'));
                         return;
                     } else {
                         if ($inscricao->id_evento != $id_evento) {
                             echo json_encode(array('erro' => 'As informações não batem! Inscrição X Evento'));
                             return;
                         }
                     }
                 }
             } else {
                 if (filter_var($identificacao, FILTER_VALIDATE_EMAIL) !== false) {
                     //                    $evento =
                     $evento = ControllerApi::getEventoAtual();
                     if ($evento == null) {
                         echo json_encode(array('erro' => 'Não existe um evento atual'));
                         return;
                     }
                     $pessoa = Pessoas::getInstance()->getByEmail(strtolower(trim($identificacao)));
                     if ($pessoa == null) {
                         echo json_encode(array('erro' => 'Não te encontramos em nossa base de dados (' . $identificacao . ')'));
                         return;
                     }
                     $inscricao = Inscricoes::getInstance()->getByEventoPessoa($evento->id, $pessoa->id);
                     if ($inscricao == null) {
                         echo json_encode(array('erro' => 'Você não se inscreveu pra este evento!'));
                         return;
                     }
                 } else {
                     echo json_encode(array('erro' => 'Do que você está falando afinal?'));
                     return;
                 }
             }
             // Fazer - retornar
             $inscricao->presenca();
             $nInscrito = ControllerApi::decorateInscricao($inscricao, true);
             $return = PLib::object_to_array($nInscrito);
             echo json_encode($return, JSON_NUMERIC_CHECK);
         });
         // Setar dados da inscrição - por enquanto apenas categoria
         $app->post('/inscricao/:idInscricao/', function ($idInscricao) use($app) {
             /* @var $inscricao Inscricao */
             $inscricao = Inscricoes::getInstance()->getById($idInscricao);
             if ($inscricao == null) {
                 echo json_encode(array('erro' => 'Inscrição não localizada na base de dados (' . $idInscricao . ')'));
                 return;
             }
             // Categoria - Como bloquear mudar a categoria? Depois de que momento não pode mudar mais?
             $id_categoria = $_POST['id_categoria'];
             $inscricao->setCategoria($id_categoria);
             $inscricao->save();
             $return = array('inscricao' => $inscricao);
             $return = PLib::object_to_array($return);
             echo json_encode($return, JSON_NUMERIC_CHECK);
         });
         // Retorna uma inscrição
         $app->get('/inscricao/:idInscricao/', function ($idInscricao) use($app) {
             /* @var $inscricao Inscricao, e o evento referente */
             $inscricao = Inscricoes::getInstance()->getById($idInscricao);
             if ($inscricao == null) {
                 echo json_encode(array('erro' => 'Inscrição não localizada na base de dados (' . $idInscricao . ')'));
                 return;
             }
             $nInscrito = ControllerApi::decorateInscricao($inscricao, true);
             $nInscrito = PLib::object_to_array($nInscrito);
             echo json_encode($nInscrito, JSON_NUMERIC_CHECK);
         });
         // Confirma um inscrito
         $app->post('/inscricao/:idInscricao/confirmar/', function ($idInscricao) use($app) {
             /* @var $inscricao Inscricao */
             $inscricao = Inscricoes::getInstance()->getById($idInscricao);
             if ($inscricao == null) {
                 echo json_encode(array('erro' => 'Inscrição não localizada na base de dados (' . $idInscricao . ')'));
                 return;
             }
             // Se evento pago, verificar se informações vieram no post
             if ($inscricao->valor_inscricao > 0 && $_POST['forma_pagamento'] == null) {
                 $return = array('erro' => 'É preciso informar a forma de pagamento da insrição.');
             } else {
                 if ($inscricao->valor_inscricao > 0 && $_POST['id_pessoa_confirmacao'] == null) {
                     $return = array('erro' => 'É preciso informar a pessoa que está confirmando o pagamento.');
                 } else {
                     if ($_POST['id_pessoa_confirmacao'] == null) {
                         $return = array('erro' => 'É preciso informar a pessoa que está confirmando a inscrição.');
                     } else {
                         if (Pessoas::getInstance()->getById($_POST['id_pessoa_confirmacao'])->id_user == null) {
                             $return = array('erro' => 'O usuário confirmando precisa ser um admin.');
                         } else {
                             $inscricao->id_pessoa_confirmacao = $_POST['id_pessoa_confirmacao'];
                             if ($inscricao->confirmado != 1) {
                                 $inscricao = $inscricao->confirmar($_POST['forma_pagamento'], $inscricao->valor_inscricao);
                             }
                             $nInscrito = ControllerApi::decorateInscricao($inscricao, true);
                             $nEvento = ControllerApi::decorateEvento($inscricao->evento(), true);
                             $return = array('evento' => $nEvento, 'inscricao' => $nInscrito);
                         }
                     }
                 }
             }
             $return = PLib::object_to_array($return);
             echo json_encode($return, JSON_NUMERIC_CHECK);
         });
         // Dá presença a um inscrito
         $app->get('/inscricao/:idInscricao/presente/', function ($idInscricao) use($app) {
             /* @var $inscricao Inscricao */
             $inscricao = Inscricoes::getInstance()->getById($idInscricao);
             if ($inscricao == null) {
                 echo json_encode(array('erro' => 'Inscrição não localizada na base de dados (' . $idInscricao . ')'));
                 return;
             }
             $inscricao = $inscricao->presenca();
             $nInscrito = ControllerApi::decorateInscricao($inscricao, true);
             $nEvento = ControllerApi::decorateEvento($inscricao->evento(), true);
             $return = array('evento' => $nEvento, 'inscricao' => $nInscrito);
             $return = PLib::object_to_array($return);
             echo json_encode($return, JSON_NUMERIC_CHECK);
         });
         // Atualiza dados de uma pessoa
         $app->post('/pessoa/:identificacao/', function ($identificacao) use($app) {
             /* @var $pessoa Pessoa */
             $identificacao = urldecode($identificacao);
             $pessoa = Pessoas::getInstance()->getByMd5($identificacao);
             if ($pessoa == null) {
                 echo json_encode(array('erro' => 'Pessoa nao localizada na base de dados (' . $identificacao . ')'));
                 return;
             }
             // Extras?
             $extras = $_POST['extras'];
             if ($extras) {
                 foreach ($extras as $chave => $valor) {
                     $pessoa->setExtra($chave, ucfirst($chave), $valor);
                 }
                 $pessoa->save();
             }
             $pessoa = Pessoas::getInstance()->getByMd5($identificacao);
             $nPessoa = ControllerApi::decoratePessoa($pessoa);
             $return = array('pessoa' => $nPessoa);
             $return = PLib::object_to_array($return);
             echo json_encode($return, JSON_NUMERIC_CHECK);
         });
         // Obter todas pessoas
         $app->get('/pessoas/todas/', function () use($app) {
             /* @var $pessoas Pessoa[] */
             $pessoas = Pessoas::getInstance()->getAll();
             $return = array();
             foreach ($pessoas as $pessoa) {
                 if ($pessoa->getCountConfirmados()) {
                     $return[] = ControllerApi::decoratePessoa($pessoa);
                 }
             }
             $return = array('pessoas' => $return);
             $return = PLib::object_to_array($return);
             echo json_encode($return, JSON_NUMERIC_CHECK);
         });
         //            $app->get('/reset/', function () use ($app) {
         //                // Zera todos os dados do site...
         //                if (DB_NAME == 'emjf_wpjf' || DB_NAME == 'emjf') {
         //                    /* @var $wpdb wpdb */
         //                    $sql = "UPDATE ev_inscricoes SET confirmado=NULL, data_pagamento=NULL, data_confirmacao=NULL, valor_pago=NULL, taxa_cobranca=NULL, valor_liquido=NULL,codigo_pagamento=NULL, formapagamento_pagseguro=NULL,presente=NULL,status_gateway=NULL,forma_pagamento_gateway=NULL,codigo_gateway=NULL,data_atualizacao_gateway=NULL,vencido=NULL,data_vencido=NULL,data_cancelamento=NULL,forma_pagamento=NULL,id_situacao=NULL";
         //                    $return = array('sucesso' => 'Dados resetados');
         //                    echo json_encode($return, JSON_NUMERIC_CHECK);
         //                } else {
         //                    $return = array('erro' => 'Ops.. aqui não pode!');
         //                    echo json_encode($return, JSON_NUMERIC_CHECK);
         //                }
         //            });
     });
     $app->run();
 }
Example #16
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 #17
0
File: index.php Project: guhya/Slim
});
$app->configureMode("production", function () use($app) {
    $app->config(array("debug" => false));
});
/******************************************** THE HOOKS ********************************************************/
$app->hook("slim.before.router", function () use($app, $twig, $util) {
    //Initial attempt to determine what menu is being requested, can be overwritten in each router
    $menu = explode("/", $app->request->getResourceUri())[1];
    $twig->addGlobal("menu", $menu);
    //Intercept session and tell view whether the user is logged in or not
    if (isset($_SESSION["user"])) {
        $twig->addGlobal("userSession", $_SESSION["user"]);
    } else {
        $twig->addGlobal("userSession", "");
    }
    //Define the page/router that begins with these segment to not initialize all gnb menu list
    $rawPages = array("ajax", "user", "social");
    //Determine whether the request is an ajax request or the normal one
    $isXHR = $app->request->isAjax();
    //If the request is an ajax type request, or the request does not need to initialize gnb (like processor page)
    //then no need to initialize gnb
    if (!$isXHR && !in_array($menu, $rawPages)) {
    } else {
        //Ajax request, do nothing
    }
}, 1);
$app->applyHook("slim.before.router");
/************************************ THE ROUTES / CONTROLLERS *************************************************/
//#################################################### HOME ####################################################
$app->get("/", function () use($app, $util) {
    $data = array("pageTitle" => "Home Page");
<?php

require 'Slim/Slim.php';
\Slim\Slim::registerAutoloader();
require 'JsonView.php';
$app = new \Slim\Slim(array('view' => new JsonView(), 'debug' => FALSE));
// All Methods
require 'router.php';
// Generic error handler
$app->error(function (Exception $e) use($app) {
    $app->render(array('error' => TRUE, 'alert' => $e->getMessage()), 500);
});
// Not found handler (invalid routes, invalid method types)
$app->notFound(function () use($app) {
    $app->render(array('error' => TRUE, 'alert' => 'Invalid route'), 404);
});
// Handle Empty response body
$app->hook('slim.after.router', function () use($app) {
    if (strlen($app->response()->body()) == 0) {
        $app->render(array('error' => TRUE, 'alert' => 'Empty response'), 500);
    }
});
$app->run();
Example #19
0
require '../vendor/autoload.php';
// Initialize Slim (the router/micro framework used).
$app = new \Slim\Slim();
// and define the engine used for the view @see http://twig.sensiolabs.org
$app->view = new \Slim\Views\Twig();
$app->view->setTemplatesDirectory("../Mini/view");
/******************************************* THE CONFIGS *******************************************************/
// Configs for mode "development" (Slim's default), see the GitHub readme for details on setting the environment
$app->configureMode('development', function () use($app) {
    // pre-application hook, performs stuff before real action happens @see http://docs.slimframework.com/#Hooks
    $app->hook('slim.before', function () use($app) {
        // SASS-to-CSS compiler @see https://github.com/panique/php-sass
        SassCompiler::run("scss/", "css/");
        // CSS minifier @see https://github.com/matthiasmullie/minify
        $minifier = new MatthiasMullie\Minify\CSS('css/style.css');
        $minifier->minify('css/style.css');
        // JS minifier @see https://github.com/matthiasmullie/minify
        // DON'T overwrite your real .js files, always save into a different file
        //$minifier = new MatthiasMullie\Minify\JS('js/application.js');
        //$minifier->minify('js/application.minified.js');
    });
    // Set the configs for development environment
    $app->config(array('debug' => true, 'database' => array('db_host' => 'localhost', 'db_port' => '', 'db_name' => 'scdm', 'db_user' => 'root', 'db_pass' => '')));
});
// Configs for mode "production"
$app->configureMode('production', function () use($app) {
    // Set the configs for production environment
    $app->config(array('debug' => false, 'database' => array('db_host' => '', 'db_port' => '', 'db_name' => '', 'db_user' => '', 'db_pass' => '')));
});
/************************************* Load Organization Defaults ***********************************************/
$organization_defaults = array('address1' => '92 High St', 'address2' => null, 'city' => 'Winter Haven', 'state' => 'FL', 'zipcode' => '33880');
Example #20
0
$app->hook('slim.before.dispatch', function () use($app) {
    if (strpos($_SERVER['REQUEST_URI'], 'login') > 0) {
        return true;
    }
    if (strpos($_SERVER['REQUEST_URI'], 'check') > 0) {
        return true;
    }
    if (!isset($_SESSION['username']) || !isset($_SESSION['token']) || !isset($_SESSION['url']) || !isset($_SESSION['report_ids'])) {
        return $app->redirect(SITE_PREFIX . 'login?redirectUrl=' . base64_encode($_SERVER['REQUEST_URI']));
    }
    $url = substr($app->request()->getPath(), strlen(SITE_PREFIX));
    if ($url == "admin/welcome") {
        return true;
    }
    if ($url == "") {
        return $app->redirect(SITE_PREFIX . 'admin/welcome');
    }
    if ($url == "logout") {
        return true;
    }
    if (strpos($url, 'user') > 0 && in_array('admin/usersmanager', $_SESSION['url'])) {
        return true;
    }
    if (strpos($url, 'report') > 0 && in_array('admin/reportsmanager', $_SESSION['url'])) {
        return true;
    }
    if (strpos($url, 'machine') !== false && in_array('machine/manager', $_SESSION['url'])) {
        return true;
    }
    if (strpos($url, 'chaxun/export') !== false) {
        return true;
    }
    if (strpos($url, 'show/export') !== false) {
        return true;
    }
    if (!isset($_SESSION['url']) || !in_array($url, $_SESSION['url'])) {
        return $app->halt('401', 'Not Authorized <a href=' . SITE_PREFIX . '/login>Login</a>');
    }
    return true;
});
Example #21
0
<?php

require 'vendor/autoload.php';
require 'site-config.php';
date_default_timezone_set('Europe/Paris');
mb_internal_encoding('UTF-8');
ORM::configure('mysql:host=' . MYSQL_HOSTNAME . ';dbname=' . MYSQL_DATABASENAME);
ORM::configure('username', MYSQL_USERNAME);
ORM::configure('password', MYSQL_PASSWORD);
ORM::configure('driver_options', array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'));
ORM::configure('return_result_sets', true);
$app = new \Slim\Slim(array('mode' => MODE, 'debug' => MODE != MODE_PROD));
$app->hook('slim.after.router', function () use($app) {
    header_remove("X-Powered-By");
});
$app->notFound(function () use($app) {
    echo "404 Not found";
});
$app->error(function (\Exception $e) use($app) {
    echo "500 Server error";
    // var_dump($e);
});
$app->group('/services', function () use($app) {
    $app->get('/data/:id/:in/:out', function ($id, $in, $out) use($app) {
        $json = array();
        if (preg_match("/^[0-9]+\$/", $id) && preg_match("/^[0-9\\-\\ \\:]+\$/", $in) && preg_match("/^[0-9\\-\\ \\:]+\$/", $out)) {
            $surveys = ORM::ForTable('lime_survey_' . $id)->where_gte('submitdate', $in)->where_lte('submitdate', $out)->order_by_asc('id')->find_many();
            foreach ($surveys as $survey) {
                $date = DateTime::createFromFormat('Y-m-d H:i:s', $survey->submitdate);
                $survey->submitdts = $date->format('U');
                // TODO: should considerate Paris Time
Example #22
0
    };
};
$app->hook('slim.before.dispatch', function () use($app) {
    global $siteName, $squareAds, $textAds, $bannerAds, $rewards, $links;
    global $cashout;
    $address = null;
    if (isset($_SESSION['address'])) {
        $address = $_SESSION['address'];
    }
    $flash = $app->view()->getData('flash');
    $error = '';
    if (isset($flash['error'])) {
        $error = $flash['error'];
    }
    $success = '';
    if (isset($flash['success'])) {
        $success = $flash['success'];
    }
    $app->view()->setData('success', $success);
    $app->view()->setData('error', $error);
    $app->view()->setData('address', $address);
    $app->view()->setData('siteName', $siteName);
    $app->view()->setData('squareAds', $squareAds);
    $app->view()->setData('textAds', $textAds);
    $app->view()->setData('bannerAds', $bannerAds);
    $app->view()->setData('rewards', $rewards);
    $app->view()->setData('links', $links);
    $app->view()->setData('cashout', $cashout);
    $app->view()->setData('isAdmin', false);
});
$app->get("/", $checkaddress($app, false), function () use($app) {
    global $minReward, $maxReward, $dispenseTimeText, $apiKey, $guid;
Example #23
0
require_once BASE_DIR . '/html/includes/api_configs.php';
require_once BASE_DIR . '/html/includes/api_folders.php';
require_once BASE_DIR . '/html/includes/api_labs.php';
require_once BASE_DIR . '/html/includes/api_networks.php';
require_once BASE_DIR . '/html/includes/api_nodes.php';
require_once BASE_DIR . '/html/includes/api_pictures.php';
require_once BASE_DIR . '/html/includes/api_status.php';
require_once BASE_DIR . '/html/includes/api_textobjects.php';
require_once BASE_DIR . '/html/includes/api_topology.php';
require_once BASE_DIR . '/html/includes/api_uusers.php';
\Slim\Slim::registerAutoloader();
$app = new \Slim\Slim(array('mode' => 'production', 'debug' => True, 'log.level' => \Slim\Log::WARN, 'log.enabled' => True, 'log.writer' => new \Slim\LogWriter(fopen('/opt/unetlab/data/Logs/api.txt', 'a'))));
$app->hook('slim.after.router', function () use($app) {
    // Log all requests and responses
    $request = $app->request;
    $response = $app->response;
    $app->log->debug('Request path: ' . $request->getPathInfo());
    $app->log->debug('Response status: ' . $response->getStatus());
});
$app->response->headers->set('Content-Type', 'application/json');
$app->response->headers->set('X-Powered-By', 'Unified Networking Lab API');
$app->response->headers->set('Cache-Control', 'no-store, no-cache, must-revalidate, max-age=0');
$app->response->headers->set('Cache-Control', 'post-check=0, pre-check=0');
$app->response->headers->set('Pragma', 'no-cache');
$app->notFound(function () use($app) {
    $output['code'] = 404;
    $output['status'] = 'fail';
    $output['message'] = $GLOBALS['messages']['60038'];
    $app->halt($output['code'], json_encode($output));
});
class ResourceNotFoundException extends Exception
Example #24
0
$status = $payutcClient->getStatus();
$app = new \Slim\Slim();
$app->hook('slim.before', function () use($app, $payutcClient, $admin) {
    // check that system is installed
    if (!Config::isInstalled()) {
        $app->flashNow('info', 'This application is not yet configured, please click <a href="install" >here</a> !');
    }
    global $status;
    if (!in_array($app->request->getResourceUri(), ['/about', '/login'])) {
        if (!isset($status) || empty($status->user)) {
            // Il n'était pas encore connecté en tant qu'icam.
            $app->flash('info', "Vous devez être connecté pour accéder au reste de l'application");
            $app->redirect('about');
        } else {
            if (!empty($status->user) && (empty($status->application) || isset($status->application->app_url) && strpos($status->application->app_url, 'shotgun') === false)) {
                // il était connecté en tant qu'icam mais l'appli non
                try {
                    $result = $payutcClient->loginApp(array("key" => Config::get('payutc_key')));
                    $status = $payutcClient->getStatus();
                } catch (\JsonClient\JsonException $e) {
                    $app->flashNow('info', "error login application, veuillez finir l'installation de Shotgun");
                    $app->redirect('install');
                }
            }
        }
        if (!empty($status->user)) {
            $_SESSION['username'] = $status->user;
        }
    }
});
// Set default data for view
$app->view->setData(array('title' => Config::get('title', 'Shotgun PayIcam')));
Example #25
0
$handlers[] = $streamToFile;
$logger_writer = new \Flynsarmy\SlimMonolog\Log\MonologWriter(array('handlers' => $handlers, 'processors' => array(new Monolog\Processor\UidProcessor(), new Monolog\Processor\WebProcessor($_SERVER))));
$app = new \Slim\Slim(array('mode' => $config['enviroment'], 'log.level' => \Slim\Log::DEBUG, 'log.enabled' => true, 'log.writer' => $logger_writer, 'templates.path' => '../templates'));
$app->config('databases', $config['databases']);
$app->add(new \BitPrepared\Slim\Middleware\EloquentMiddleware());
$corsOptions = array("origin" => "*");
$app->add(new \CorsSlim\CorsSlim($corsOptions));
$app->hook('slim.before.router', function () use($app) {
    $req = $app->request;
    $allGetVars = $req->get();
    $allPostVars = $req->post();
    $allPutVars = $req->put();
    $vars = array_merge($allGetVars, $allPostVars);
    $vars = array_merge($vars, $allPutVars);
    $srcParam = json_encode($vars);
    $srcUri = $req->getRootUri();
    $srcUrl = $req->getResourceUri();
    //$app->log->info(@Kint::dump( $srcUrl ));
    $app->log->debug('REQUEST : ' . var_export($_REQUEST, true));
    // Sono stati messi nel log dal logger
    // $app->log->debug('URI : '.$srcUri);
    // $app->log->debug('URL : '.$srcUrl);
    $app->log->debug('Params : ' . $srcParam);
    $req->isAjax() ? $app->log->debug('Ajax attivo') : $app->log->debug('Ajax non attivo');
});
$app->hook('slim.after.dispatch', function () use($app) {
    $status = $app->response->getStatus();
    $app->log->debug('terminato con stato [' . $status . ']');
});
// $log = $app->getLog();
// $view = $app->view();
$app->configureMode('development', function () use($app, $config) {
Example #26
0
    }
}
define("CDN_URL", getCDNPath());
require 'vendor/autoload.php';
require 'models/TaxCalculator.php';
require 'models/StateTaxCalculator.php';
require 'models/FederalTaxCalculator.php';
$state_calculator = new StateTaxCalculatorModel();
$federal_calculator = new FederalTaxCalculatorModel();
$app = new \Slim\Slim();
// Parse the response and display it.
$app->hook('respond', function ($response) use($app) {
    $app->response->header('Access-Control-Allow-Origin', '*');
    $app->response->headers->set('Content-Type', 'application/json');
    if ($response['success'] === false) {
        $app->halt(400, "{\"success\": false, \"reason\": \"" . $response['reason'] . "\"}");
    } else {
        echo json_encode($response['data']);
    }
});
$app->get('/v1/federal/:year/', function ($year) use($app, $federal_calculator) {
    $response = $federal_calculator->get_federal_data($year);
    $app->applyHook('respond', $response);
});
$app->get('/v1/state/:state/:year/', function ($year, $state) use($app, $state_calculator) {
    $response = $state_calculator->get_state_data($year, $state);
    $app->applyHook('respond', $response);
});
$app->post('/v1/calculate/:year/', function ($year) use($app, $state_calculator, $federal_calculator) {
    $pay_rate = $app->request->post('pay_rate');
    $pay_periods = $app->request->post('pay_periods') == false ? 1 : $app->request->post('pay_periods');
Example #27
0
    } else {
        return $r;
    }
    $c = explode(':', $sesija);
    $s = $em->find('Sesija', $c[1]);
    if ($s->getKljuc() == $c[0] && $s->getValidna()) {
        $r['status'] = true;
        $r['korisnik'] = $s;
        $r['korisnik_string'] = var_export($s, true);
        return $r;
    } else {
        setcookie('session', '', time() - 60 * 60 * 24 * 30, $urls['rootUri'] . '/');
    }
}
$app->hook('slim.before.router', function () use($app) {
    $env = $app->environment();
    $env['ulogovan'] = is_ulogovan($app->request->params('session'));
});
function is_android()
{
    global $app;
    return stristr($app->request->headers->get('USER_AGENT'), 'Android') != false ? true : false;
}
$acl_map = array(500 => 'admin', 501 => 'editor', 502 => 'chat', 503 => 'user', 'admin' => 500, 'editor' => 501, 'chat' => 502, 'user' => 503);
$login = function ($rola = 'user') {
    global $app, $acl_map;
    $env = $app->environment();
    return function () use($app, $rola, $env, $acl_map) {
        if (!$env['ulogovan']['status']) {
            $app->redirect('/login/');
        } else {
            if (intval($env['ulogovan']['korisnik']->getRola()) > $acl_map[$rola]) {
Example #28
0
<?php

require 'vendor/autoload.php';
$app = new \Slim\Slim(array('debug' => true, 'templates.path' => './controllers'));
$app->view->parserOptions = array('charset' => 'utf-8', 'cache' => realpath('./cache'), 'auto_reload' => true, 'strict_variables' => false, 'autoescape' => true);
$header = array('file' => 'header.php', 'params' => array("title" => "!Bangs", "description" => "Add the !Bang effect to your favourite search engine!", "content" => ""));
$favicon = '<link rel="icon" type="image/png" href="https://www.google.com/s2/favicons?domain=http://duckduckgo.com"/>';
$domain = 'https://bangs.bonduel.net/';
$app->hook('slim.before', function () use($app, $domain) {
    $app->view()->appendData(array('baseUrl' => ''));
    $app->view()->appendData(array('domain' => $domain));
});
$app->post('/', function () use($app, $header) {
    $ddgSuggestion = $app->request->post('ddgSuggestions') == "on" ? true : false;
    $app->render('generate.php', array('app' => $app, 'type' => $app->request->post('type'), 'ddgSuggestion' => $ddgSuggestion, 'content' => $app->request->post('content'), 'header' => $header));
});
$app->get('/', function () use($app, $header, $favicon, $domain) {
    if (!isset($_SERVER['HTTPS']) || empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'off') {
        header("HTTP/1.1 301 Moved Permanently");
        header("Location: " . $domain);
        die;
    }
    $header['params']['content'] .= $favicon;
    $app->render('template.php', array('app' => $app, 'content' => array('nav' => 'home', 'file' => 'forms.php', 'params' => array()), 'header' => $header));
});
$app->get('/su/:url', function ($url) use($app, $header, $favicon) {
    $header['params']['content'] .= $favicon;
    $app->render('template.php', array('app' => $app, 'content' => array('nav' => 'home', 'file' => 'forms.php', 'params' => array('url' => htmlspecialchars($url, ENT_QUOTES, 'UTF-8'))), 'header' => $header));
});
$app->get('/about', function () use($app, $header, $favicon) {
    $header['params']['content'] .= $favicon;
Example #29
0
 /**
  * Test hooks accept multiple arguments
  *
  * Pre-conditions:
  * Slim app instantiated;
  * Hook name does not exist;
  * Listener is a callable object;
  *
  * Post-conditions:
  * Callable invoked with 2 arguments
  */
 public function testHooksMultipleArguments()
 {
     $testArgA = 'argumentA';
     $testArgB = 'argumentB';
     $this->expectOutputString($testArgA . $testArgB);
     $app = new \Slim\Slim();
     $app->hook('test.hook.one', function ($argA, $argB) {
         echo $argA . $argB;
     });
     $app->applyHook('test.hook.one', $testArgA, $testArgB);
 }
Example #30
0
$app->leaderboard = function () {
    return new \SimpleQuiz\Utils\LeaderBoard();
};
$app->quiz = function ($app) {
    return new \SimpleQuiz\Utils\Quiz($app);
};
$app->admin = function ($app) {
    return new \SimpleQuiz\Utils\Admin($app);
};
$app->simple = function () {
    return new \SimpleQuiz\Utils\Simple();
};
$app->installer = function () {
    return new \SimpleQuiz\Utils\Base\Installer();
};
$app->hook('slim.before.dispatch', function () use($app) {
    $user = null;
    $requireauth = SimpleQuiz\Utils\Base\Config::$requireauth;
    //if no auth required to take quizzes, set a default user
    if (!$requireauth) {
        $app->session->set('user', SimpleQuiz\Utils\Base\Config::$defaultUser);
    }
    if ($app->session->get('user')) {
        $user = $app->session->get('user');
    }
    $app->view()->appendData(['user' => $user]);
    $app->view()->appendData(['requireauth' => $requireauth]);
    $root = $app->request->getRootUri();
    $app->view()->appendData(['root' => $root]);
});
$app->run();