/**
  * Test get log
  *
  * This asserts that a Slim app has a default Log
  * upon instantiation. The Log itself is tested
  * separately in another file.
  */
 public function testGetLog()
 {
     $s = new \Slim\Slim();
     $this->assertInstanceOf('\\Slim\\Log', $s->getLog());
 }
<?php

include __DIR__ . '/vendor/autoload.php';
include __DIR__ . '/../../bootstrap.php';
$debugbarRenderer->setBaseUrl('../../../src/DebugBar/Resources');
$app = new \Slim\Slim();
$app->get('/', function () use($app) {
    $app->getLog()->info('hello world');
    render_demo_page();
});
$debugbar->addCollector(new DebugBar\Bridge\SlimCollector($app));
$app->run();
Example #3
0
// ========== COMPOSER ==========
require ROOT_PATH . '/vendor/autoload.php';
// ========== CONFIGURATION ==========
$config = (require APP_PATH . '/src/config.php');
// ========== PHP (from configuration) ==========
// time zone
date_default_timezone_set($config['PHP']['default_timezone']);
// errors
ini_set('display_errors', $config['PHP']['display_errors']);
ini_set('display_startup_errors', $config['PHP']['display_startup_errors']);
ini_set('log_errors', $config['PHP']['log_errors']);
// session
if (true === $config['PHP']['need_session']) {
    session_cache_limiter(false);
    session_set_cookie_params(0, '/', '', $config['PHP']['session_cookie_secure'], true);
    session_start();
}
unset($config['PHP']);
// ========== SLIM ==========
$app = new \Slim\Slim($config['Slim']);
$app->config('app', $config['App']);
$app->view()->setData('config', $app->config('app'));
require APP_PATH . '/src/dependencies.php';
require APP_PATH . '/src/middlewares.php';
require APP_PATH . '/src/routes.php';
// Error handler
$app->error(function (\Exception $e) use($app) {
    $app->getLog()->error($e);
    $app->render('errors/error.twig');
});
$app->run();
Example #4
0
         }
         $mongoCollection = getMongoCollection('user');
         foreach ($post as $key => $value) {
             $encode = mb_detect_encoding($value, array('UTF-8'));
             if ($encode !== 'UTF-8') {
                 throw new RuntimeException('メールアドレスまたはパスワードに誤りがあります');
             }
         }
         $result = $mongoCollection->find(array('email' => $post['email'], 'password' => getPasswordHash($post['email'], $post['password'], $app->config('salt'))));
         if ($result->count()) {
             session_regenerate_id(true);
             $user = $result->next();
             $_SESSION['user'] = $user;
             $_SESSION['expires'] = time() + (int) $app->config('timeout');
             $app->flash('info', 'ログインしました。');
             $app->getLog()->info('ユーザー名「' . $user['username'] . '」(メールアドレス"' . $user['email'] . '")がログインしました。');
             $app->redirect($app->config('static_path'));
         } else {
             throw new RuntimeException('メールアドレスまたはパスワードに誤りがあります');
         }
     } catch (RuntimeException $e) {
         $app->flash('error', $e->getMessage());
         $app->redirect($app->config('static_path') . 'login');
     }
 });
 $app->map('/logout', function () use($app) {
     if (isset($_SESSION['user'])) {
         $app->getLog()->info('ユーザー名「' . $_SESSION['user']['username'] . '」(メールアドレス"' . $_SESSION['user']['email'] . '")がログアウトしました。');
     }
     session_destroy();
     session_regenerate_id(true);
Example #5
0
 * @author      Damian Worsdell <*****@*****.**>
 * @copyright   Copyright (C) 2015, Damian Worsdell and Bloom Labs, Inc.
 */
// Define our Namespace
namespace Bloom\Schedule\API;

use Bloom\Schedule\API\Model\Booking;
use Bloom\Schedule\API\Model\Statistics;
// Auto-load the classes via Composer's PSR-4 autoloader
require 'vendor/autoload.php';
// Configure log writer
$config['app']['log.writer'] = new \Flynsarmy\SlimMonolog\Log\MonologWriter(array('handlers' => array(new \Monolog\Handler\StreamHandler('data/logs/' . date('Y-m-d') . '.log'))));
// Start Slim
$app = new \Slim\Slim($config['app']);
// Start log writer
$log = $app->getLog();
// Set response headers
$app->response->headers->set('Content-Type', 'application/json;charset=utf-8');
$app->etag(md5(time()));
// Define path & URL
$req = $app->request;
define('ROOT', $req->getPath());
define('URL', $req->getUrl());
// Bookings
$app->group('/booking', function () use($app, $log) {
    // Returns the details of all current and future bookings
    $app->get("/all", function () use($app, $log) {
        Booking::all($app);
    });
    // Returns the details of the next bookings for room number of :room
    $app->get("/next/:room", function ($room) use($app, $log) {
Example #6
0
     $_SESSION[$download['id']] = array();
 } else {
     if ($download['status'] == Status::DOWNLOADING) {
         if ($activeDownloads >= 3) {
             continue;
         }
         $activeDownloads++;
         try {
             $_SESSION[$download['id']][] = (array) getChapter($download['story']['url'], $download['currentChapter'], $download['story']['metadata']);
             if ($download['currentChapter'] == $download['totalChapters']) {
                 $download['status'] = Status::DOWNLOAD_COMPLETE;
             } else {
                 $download['currentChapter']++;
             }
         } catch (Exception $ex) {
             $app->getLog()->error($ex);
             $download['status'] = Status::ERROR;
             $download['statusMessage'] = "Failed to download chapter {$download['currentChapter']}.";
             unset($_SESSION[$download['id']]);
         }
     } else {
         if ($download['status'] == Status::DOWNLOAD_COMPLETE) {
             $download['status'] = Status::BUILDING;
         } else {
             if ($download['status'] == Status::BUILDING) {
                 if ($activeBuilds >= 1) {
                     continue;
                 }
                 $activeBuilds++;
                 try {
                     $book = new \PHPePub\Core\EPub();
Example #7
0
<?php

require_once 'env.php';
require_once APP_DIR . '/vendor/autoload.php';
$app = new \Slim\Slim(array('debug' => false, 'cookies.encrypt' => true, 'cookies.secret_key' => 'd3@SD#@!TXZE@', 'cookies.cipher' => MCRYPT_RIJNDAEL_256, 'cookies.cipher_mode' => MCRYPT_MODE_CBC, 'log.enabled' => true, 'log.writer' => new src\common\LogWriter(), 'log.level' => \Slim\Log::DEBUG));
//处理request数据类型
$app->add(new \Slim\Middleware\ContentTypes());
$app->notFound(function () use($app) {
    $app->getLog()->warning('url not found:' . $app->request()->getResourceUri());
    $app->render('404.html');
});
//处理所有未catch exception
$app->error(function (Exception $e) use($app) {
    $app->getLog()->critical('server error: ' . $e->getMessage());
    $app->halt(500, "sorry! server error");
});
$request = $app->request();
$paths = explode('/', $request->getResourceUri());
if (count($paths) < 4 || strtolower($paths[1]) != 'api') {
    $app->getLog()->error('bad request:' . $request->getResourceUri());
    $app->status(400);
}
$app->group('/api', function () use($app, $paths) {
    $router = ucfirst(strtolower($paths[2]));
    if (!file_exists(APP_DIR . "/src/routers/{$router}.php")) {
        return;
    }
    $app->group("/{$paths['2']}", function () use($app, $router) {
        $routerClass = "src\\routers\\{$router}";
        new $routerClass($app);
    });
Example #8
0
        $namespace = substr($className, 0, $lastNsPos);
        $className = substr($className, $lastNsPos + 1);
        $fileName .= str_replace('\\', DIRECTORY_SEPARATOR, $namespace) . DIRECTORY_SEPARATOR;
    }
    $fileName .= str_replace('_', DIRECTORY_SEPARATOR, strtolower($className)) . '.php';
    // error_log($fileName);
    if (file_exists($fileName)) {
        return require $fileName;
    }
});
// Initialize Slim:
$app = new \Slim\Slim(array('templates.path' => ROOT . '/templates', 'log.enabled' => true));
// Load config management library:
require ROOT . '/common/config.php';
// Set logging level:
$log = $app->getLog();
$log->setLevel(config('log.level', 0));
// Load default libraries:
require ROOT . '/common/memcached.php';
require ROOT . '/common/db.php';
require ROOT . '/common/session.php';
// Setup the slim.after hook for printing DB log
$app->hook('slim.after', function () use($app) {
    foreach (ORM::get_query_log() as $entry) {
        $app->getLog()->debug($entry);
    }
});
// Add API functionality
if (config('use.api', false)) {
    require ROOT . '/common/api.php';
}
Example #9
0
$app->get("/install", function () use($app, $facebook) {
    $app->render("install.html", array("app_id" => $facebook->getAppId()));
});
/* Facebook converts GET request to POST. Provide both for easier */
/* development. */
$app->map("/tab", function () use($app, $facebook) {
    $signed_request = $facebook->getSignedRequest();
    /* If you need to like gate (yuck) you can do something like
       if ($signed_request["page"]["liked"]) {
           render liked tab
       } else {
           render not liked tab
       }
       */
    $app->render("tab.html", array("facebook" => $facebook, "app" => $app));
    $app->getLog()->info("Tab rendered");
})->via("GET", "POST");
/* User gave permissions to application. */
$app->post("/entries", function () use($app, $facebook) {
    /* Creates new user with uid, oauth_token and name if does not exist. */
    $user = current_user();
    /* Save extra data if needed. */
    /*
    $user->foo = $app->request()->post("foo");
    $user->save();
    */
    /* Also log to a file. */
    $message = sprintf("%s (%s) participated in campaign (%s)", $user->name, $user->uid, $_SERVER["REMOTE_ADDR"]);
    $app->getLog()->info($message);
    $data["status"] = "ok";
    $app->contentType("application/json");
Example #10
0
$env = $app->environment();
$app->configureMode('live', function () use($app, $env) {
    $env['URLBASE'] = 'http://nesbot.com';
    $env['URLIMG'] = '/img/';
    $env['URLFULLIMG'] = $env['URLBASE'] . $env['URLIMG'];
    $env['URLCSS'] = '/css/';
    $env['URLJS'] = '/js/';
    $env['GATRACKER'] = 'UA-5684902-5';
    $app->config('debug', false);
    $logWriter = new \Slim\Extras\Log\DateTimeFileWriter(array('path' => __DIR__ . '/../logs'));
});
$app->configureMode('local', function () use($app, $env) {
    $env['URLBASE'] = 'http://127.0.0.1';
    $env['URLIMG'] = '/img/';
    $env['URLFULLIMG'] = $env['URLBASE'] . $env['URLIMG'];
    $env['URLCSS'] = '/css/';
    $env['URLJS'] = '/js/';
    //$env['GATRACKER'] = '';
    $app->config('debug', true);
    $out = array();
    exec(sprintf("php %s/bundle.php", __DIR__), $out);
    if (count($out) > 1) {
        printf('<div><pre><code>%s</code></pre></div>', implode(PHP_EOL, $out));
    }
    $logWriter = new \Slim\Extras\Log\DateTimeFileWriter(array('path' => __DIR__ . '/logs'));
});
$app->getLog()->setWriter($logWriter);
$posts = (require 'posts.php');
$app->view(new BlogView($app, 'template.php', $posts));
require 'routes.php';
$app->run();