Example #1
1
<?php

require 'Slim/Slim.php';
//With custom settings
$app = new Slim();
//Mailchimp help route
$app->get('/mailchimp', function () use($app) {
    $app->render('mailchimp.php');
});
//Mailchimp webhook
$app->post('/mailchimp', function () use($app) {
    require_once 'MCAPI.class.php';
    $emailField = $app->request()->get('email');
    $listId = $app->request()->get('listid');
    $apiKey = $app->request()->get('apikey');
    //Make sure we have required data.
    if (empty($emailField) || empty($listId) || empty($apiKey)) {
        $app->halt(500, 'Your hook is missing required GET parameters.');
    }
    $email = $app->request()->post($emailField);
    $forename = $app->request()->post($app->request()->get('forename'));
    $surname = $app->request()->post($app->request()->get('surname'));
    $rid = $app->request()->post('id');
    //Make sure we have required data.
    if (empty($email)) {
        $app->halt(500, 'Your hook is missing email address.');
    }
    //If double opt in parameter is present, subscribe with double opt-in.
    $doubleOptIn = false;
    if (!is_null($app->request()->get('doubleoptin'))) {
        $doubleOptIn = true;
Example #2
0
File: User.php Project: stojg/puny
 /**
  *
  * @param Slim $app
  * @return boolean
  */
 public function login($app)
 {
     if (!$app->request()->isPost()) {
         return false;
     }
     $this->setUsername($app->request()->params('username'));
     $this->setPassword($app->request()->params('password'));
     return $this->valid();
 }
Example #3
0
 private function getRouting()
 {
     /** anomymous functions are supported by php >= 5.3 
      **/
     /*$this->get('/admin(/:options)', function ($options='(not set)') {
     			echo 'Hello admin! This is a dummy siteaccess for admins only.';
     			echo '<br />';
     			echo 'Your option is: '.$options;
     		});*/
     /**
      * This gets tne navigation model and current page object
      */
     #phpinfo();
     $app = new Slim();
     $request = $app->request();
     // Deletes Get-Parms
     self::$URI = $app->request()->getResourceUri();
     /*show(self::$URI);
     		show($request);
     		show ($_SERVER['PATH_INFO']);
     		*/
     /**/
     /**
      * WALK all Single, get Param and make Routing 
      * **/
     $this->_Navigation = $this->_getNavigationModel();
     $this->page = $this->_Navigation->getCurrent();
     if ($app->request()->isAjax()) {
         $this->get($this->page->url, $this->getAjax($this->page));
     } else {
         $this->get($this->page->url, $this->getPage($this->page));
     }
     /*
     $this->get('/', function () {
     	show ('Hello world! This is the root node.');
     });
     
     $this->get('/me', function () {
     	echo 'Hello world! You know me?';
     });
     
     $this->get(self::$URI, function () {
     	echo 'Hello world! This is very generic!!!';
     });
     */
     // ToDos
     // redirection
     // hardcoded link?!
     // Logik vor modules?
     // JS-Linking
     // else: We should determine a 404-error for files like Google authorization files
 }
Example #4
0
 /**
  * Test default instance properties
  */
 public function testDefaultInstanceProperties()
 {
     $s = new Slim();
     $this->assertInstanceOf('Slim_Http_Request', $s->request());
     $this->assertInstanceOf('Slim_Http_Response', $s->response());
     $this->assertInstanceOf('Slim_Router', $s->router());
     $this->assertInstanceOf('Slim_View', $s->view());
     $this->assertInstanceOf('Slim_Log', $s->getLog());
     $this->assertEquals(Slim_Log::DEBUG, $s->getLog()->getLevel());
     $this->assertTrue($s->getLog()->getEnabled());
     $this->assertInstanceOf('Slim_Environment', $s->environment());
 }
Example #5
0
include_once './libs/Slim/Slim.php';
require_once './classes/dbHelper.php';
$app = new Slim();
$db = new dbHelper();
$app->get('/getperguntas/:idpalestra', function ($idpalestra) use($app) {
    global $db;
    $stmt = $db->selectperguntas("perguntaspalestras", "id,pergunta,nomeusuario", " idpalestra = '{$idpalestra}'");
    echo json_encode($stmt);
});
$app->post('/avaliarpalestra', function () use($app) {
    global $db;
    $idpalestra = "palestra01";
    $nota = 3;
    $email = "*****@*****.**";
    $db->insert("avaliacao", array("idpalestra" => $idpalestra, "email" => $email, "nota" => $nota));
});
$app->post('/cadastrapergunta', function () use($app) {
    global $db;
    $postvalores = $app->request()->post();
    $idpalestra = $postvalores['idpalestra'];
    $pergunta = $postvalores['pergunta'];
    $nomeusuario = $postvalores['nomeusuario'];
    $db->insert("perguntaspalestras", array("idpalestra" => $idpalestra, "pergunta" => $pergunta, "nomeusuario" => $nomeusuario));
});
$app->get('/', function () use($app) {
    $app->render('home.php');
});
$app->get('/iframe', function () use($app) {
    $app->render('iframe.php');
});
$app->run();
Example #6
0
File: Slim.php Project: ntdt/Slim
 /**
  * Default Not Found handler
  *
  * @return void
  */
 public static function defaultNotFound() {
     echo self::generateTemplateMarkup('404 Page Not Found', '<p>The page you are looking for could not be found. Check the address bar to ensure your URL is spelled correctly. If all else fails, you can visit our home page at the link below.</p><a href="' . Slim::request()->getRootUri() . '">Visit the Home Page</a>');
 }
 /**
  * Slim's request object
  *
  * @return \Slim\Http\Request
  */
 protected function request()
 {
     return $this->app->request();
 }
Example #8
0
    $user->getFriends($id);
});
$app->get('/users/:id/score', function ($id) use($user) {
    $user->getScore($id);
});
$app->get('/users/:id/rewards', function ($id) use($user) {
    $user->getRewards($id);
});
$app->get('/users/search/:name', function ($name) use($user) {
    $user->getByName($name);
});
$app->delete('/users/:id', function ($id) use($user) {
    $user->delete($id);
});
$app->post('/users', function () use($user, $app) {
    $request = $app->request();
    $body = $request->getBody();
    $vo = json_decode($body);
    $user->insert($vo);
});
$app->put('/users/:id', function ($id) use($user, $app) {
    $request = $app->request();
    $body = $request->getBody();
    $vo = json_decode($body);
    $vo->facebook_user_id = $id;
    $user->update($vo);
});
$app->put('/users/:id/score', function ($id) use($user, $app) {
    $request = $app->request();
    $body = $request->getBody();
    $vo = json_decode($body);
Example #9
0
Slim::put('/put', function () {
    echo '<p>Here are the details about your PUT request:</p>';
    print_r(Slim::request());
});
//Sample PUT route for PHP <5.3
/*
Slim::put('/put', 'put_example');
function put_example() {
	echo '<br/><br/>Here are the details about your PUT request:<br/><br/>';
	print_r(Slim::request());
}
*/
//Sample DELETE route for PHP >=5.3
Slim::delete('/delete', function () {
    echo '<p>Here are the details about your DELETE request:</p>';
    print_r(Slim::request());
});
//Sample DELETE route for PHP <5.3
/*
Slim::delete('/delete', 'delete_example');
function delete_example() {
	echo '<br/><br/>Here are the details about your DELETE request:<br/><br/>';
	print_r(Slim::request());
}
*/
/*** NAMED ROUTES *****/
Slim::get('/hello/:name', function ($name) {
    echo "<p>Hello, {$name}!</p>";
    echo "<p>This route using name \"Bob\" instead of \"{$name}\" would be: " . Slim::urlFor('hello', array('name' => 'Bob')) . '</p>';
})->name('hello')->conditions(array('name' => '\\w+'));
/*** RUN SLIM ***/
Example #10
0
/* == *
 *
 * FILTERS
 *
 * ==============================================*/
$app->hook('test.filer', function ($argument) {
    return $argument;
});
// End FILTERS
/* == *
 *
 * ROUTES
 *
 * ==============================================*/
$app->map('/', function () use($app) {
    if ($app->request()->isPost() && sizeof($app->request()->post()) == 2) {
        // if valid login, set auth cookie and redirect
        $testp = sha1('uAX8+Tdv23/3YQ==');
        $post = (object) $app->request()->post();
        if (isset($post->username) && isset($post->password) && sha1($post->password) == $testp && $post->username == 'bppenne') {
            //$app->setEncryptedCookie('bppasscook', $post->password, 0);
            $app->setCookie('user_cook', $post->username, 0);
            $app->setCookie('pass_cook', $post->password, 0);
            $app->redirect('./review');
        } else {
            $app->redirect('.');
        }
    }
    $app->render('login.html');
})->via('GET', 'POST')->name('login');
$authUser = function ($role = 'member') use($app) {
Example #11
0
require "libs/Simplepie/autoloader.php";
//Autoload para as Classes do SimplePie, para leitura de RSS
require "libs/Slim/Slim.php";
//Micro-framework Slim, para gerenciamento de rotas e alguns Helpers
include "app/funcoes.php";
//Funções próprias, como CSS, Javascript e Meta
include "app/config.php";
//Configurações gerais do sistema, através de Constantes.
date_default_timezone_set('America/Sao_Paulo');
$autoloader = new Autoloader();
$app = new Slim();
$app->contentType('text/html; charset=utf-8');
$app->add(new Slim_Middleware_SessionCookie(array('secret' => '98897qwer65465qwe9r79qw9e354as68dh56k6lks6df8g', 'expires' => '60 minutes')));
$authenticate = function ($app) {
    return function () use($app) {
        if (!isset($_SESSION['dehbora']['user'])) {
            $_SESSION['dehbora']['urlRedirect'] = $app->request()->getPathInfo();
            $app->flash('error', 'Você precisa se logar.');
            $app->redirect(URL_BASE . '/inicial');
        }
    };
};
$app->hook('slim.before.dispatch', function () use($app) {
    $user = null;
    if (isset($_SESSION['dehbora']['user'])) {
        $user = $_SESSION['dehbora']['user'];
    }
    $app->view()->setData('user', $user);
});
require_once "app/routes.php";
$app->run();
Example #12
0
 public function testSlimAccessors()
 {
     $app = new Slim();
     $this->assertTrue($app->request() instanceof Slim_Http_Request);
     $this->assertTrue($app->response() instanceof Slim_Http_Response);
     $this->assertTrue($app->router() instanceof Slim_Router);
 }
Example #13
0
    }
    return $app->render('blog_detail.html', array('article' => $article));
});
// Admin Home.
$app->get('/admin', $authCheck, function () use($app) {
    $articles = Model::factory('Article')->order_by_desc('timestamp')->find_many();
    return $app->render('admin_home.html', array('articles' => $articles));
});
// Admin Add.
$app->get('/admin/add', $authCheck, function () use($app) {
    return $app->render('admin_input.html', array('action_name' => 'Add', 'action_url' => '/microframework/admin/add'));
});
// Admin Add - POST.
$app->post('/admin/add', $authCheck, function () use($app) {
    $article = Model::factory('Article')->create();
    $article->title = $app->request()->post('title');
    $article->author = $app->request()->post('author');
    $article->summary = $app->request()->post('summary');
    $article->content = $app->request()->post('content');
    $article->timestamp = date('Y-m-d H:i:s');
    $article->save();
    $app->redirect('/microframework/admin');
});
// Admin Edit.
$app->get('/admin/edit/(:id)', $authCheck, function ($id) use($app) {
    $article = Model::factory('Article')->find_one($id);
    if (!$article instanceof Article) {
        $app->notFound();
    }
    return $app->render('admin_input.html', array('action_name' => 'Edit', 'action_url' => '/microframework/admin/edit/' . $id, 'article' => $article));
});
Example #14
0
});
$app->map('/connect/', function () use($app) {
    $params = App::start();
    $params['title'] = "Connect";
    $params['page'] = "connect";
    $params['errors'] = array();
    # This user already has an active session
    if (App::user()) {
        $user = App::getUser();
        $params['user_email'] = $user->email;
        $params['user_name'] = $user->first_name . ' ' . $user->last_name;
        $params['button'] = "Logout";
    } else {
        # This user is not yet authenticated
        #  (it is their first visit, or they were redirected here after logout)
        if ($app->request()->get('code')) {
            # This user has just authenticated, get their access token and store it
            $connect = App::connect($app->request()->get('code'));
            if (array_key_exists('error', $connect)) {
                $params['errors'][] = $connect['error'];
            } else {
                if (array_key_exists('access_token', $connect)) {
                    App::begin($connect['access_token'], 1);
                    $user = App::getUser($connect['access_token']);
                    $params['user_email'] = $user->email;
                    $params['user_name'] = $user->first_name . ' ' . $user->last_name;
                    $params['button'] = "Logout";
                }
            }
        } else {
            if ($app->request()->get('error') == 'access_denied') {
Example #15
0
 /**
  * Warpper function to get host URL.
  * From site.baseurl or auto detected by Slim.
  *
  * @return Host URL string
  */
 public function getUrl()
 {
     return $this->getConfig('site.baseurl') ? $this->getConfig('site.baseurl') : $this->slim->request()->getUrl();
 }
Example #16
0
    $data['tasks'] = Task::find('all');
    $app->render('task/index.php', $data);
})->name('tasks');
$app->post('/task/new/', function () use($app) {
    $task = new Task();
    $task->name = "My New Task";
    $task->done = 0;
    $task->save();
    if ($task->id > 0) {
        $app->redirect($app->urlFor('tasks'));
    }
})->name('task_new');
$app->get('/task/:id/edit', function ($id) use($app) {
    $data['task'] = Task::find($id);
    $app->render('task/edit.php', $data);
})->name('task_edit');
$app->post('/task/:id/edit', function ($id) use($app) {
    $task = Task::find($id);
    $task->name = $app->request()->post('name');
    $task->done = $app->request()->post('done') === '1' ? 1 : 0;
    $task->save();
    if ($task->id > 0) {
        $app->redirect($app->urlFor('tasks'));
    }
})->name('task_edit_post');
$app->get('/task/:id/delete', function ($id) use($app) {
    $task = Task::find($id);
    $task->delete();
    $app->redirect($app->urlFor('tasks'));
})->name('task_delete');
$app->run();
    }
    $app->response()->header("Content-Type", "application/json");
    echo json_encode($books);
});
$app->get("/book/:id", function ($id) use($app, $db) {
    $app->response()->header("Content-Type", "application/json");
    $book = $db->books()->where("id", $id);
    if ($data = $book->fetch()) {
        echo json_encode(array("id" => $data["id"], "title" => $data["title"], "author" => $data["author"], "summary" => $data["summary"]));
    } else {
        echo json_encode(array("status" => false, "message" => "Book ID {$id} does not exist"));
    }
});
$app->post("/book", function () use($app, $db) {
    $app->response()->header("Content-Type", "application/json");
    $book = $app->request()->post();
    $result = $db->books->insert($book);
    echo json_encode(array("id" => $result["id"]));
});
$app->put("/book/:id", function ($id) use($app, $db) {
    $app->response()->header("Content-Type", "application/json");
    $book = $db->books()->where("id", $id);
    if ($book->fetch()) {
        $post = $app->request()->put();
        $result = $book->update($post);
        echo json_encode(array("status" => (bool) $result, "message" => "Book updated successfully"));
    } else {
        echo json_encode(array("status" => false, "message" => "Book id {$id} does not exist"));
    }
});
$app->delete("/book/:id", function ($id) use($app, $db) {
Example #18
0
    $selectedLanguage = $_POST["language"];
    $_SESSION["language"] = $selectedLanguage;
} elseif (isset($_SESSION["language"]) && in_array($_SESSION["language"], $allowedLanguages)) {
    $selectedLanguage = $_SESSION["language"];
} else {
    $_SESSION["language"] = $selectedLanguage;
}
$language = (require dirname(__FILE__) . "/assets/lang/{$selectedLanguage}.php");
// Initiate slim
$app = new Slim();
// Assign components
$app->config('install.requirements', new Shopware_Install_Requirements());
$app->config('install.requirementsPath', new Shopware_Install_Requirements_Path());
$app->config('install.language', $selectedLanguage);
// Save post - parameters
$params = $app->request()->params();
foreach ($params as $key => $value) {
    if (strpos($key, "c_") !== false) {
        $_SESSION["parameters"][$key] = $value;
    }
}
// Initiate database object
$databaseParameters = array("user" => isset($_SESSION["parameters"]["c_database_user"]) ? $_SESSION["parameters"]["c_database_user"] : "", "password" => isset($_SESSION["parameters"]["c_database_user"]) ? $_SESSION["parameters"]["c_database_password"] : "", "host" => isset($_SESSION["parameters"]["c_database_user"]) ? $_SESSION["parameters"]["c_database_host"] : "", "port" => isset($_SESSION["parameters"]["c_database_user"]) ? $_SESSION["parameters"]["c_database_port"] : "", "database" => isset($_SESSION["parameters"]["c_database_user"]) ? $_SESSION["parameters"]["c_database_schema"] : "");
$app->config("install.database.parameters", $databaseParameters);
$app->config('install.database', new Shopware_Install_Database($databaseParameters));
function getShopDomain()
{
    $domain = $_SERVER["HTTP_HOST"];
    $basepath = str_replace("/check/index.php", "", $_SERVER["SCRIPT_NAME"]);
    return array("domain" => $domain, "basepath" => $basepath);
}
<?php

require "Slim/Slim.php";
$app = new Slim();
$app->contentType('application/json');
//$app->post('/{lado1}/{lado2}/{lado3}', function($lado1, $lado2, $lado3) use($app) {
$app->post('/calcular', function () use($app) {
    //$request = $app->request();
    //$body = $request->getBody();
    //$input = json_decode($body);
    //$lado1 = $input->lado1;
    //$lado2 = $input->lado2;
    //$lado3 = $input->lado3;
    //print_r();
    $lado1 = $app->request()->params("lado1");
    $lado2 = $app->request()->params("lado2");
    $lado3 = $app->request()->params("lado3");
    if ($lado1 <= 0 || $lado2 <= 0 || $lado3 <= 0) {
        echo json_encode(array('status' => false, 'lado1' => $lado1, 'lado2' => $lado2, 'lado3' => $lado3, 'resultado' => "Lado menor ou igual a zero"));
    } else {
        if ($lado1 == $lado2 && $lado2 == $lado3) {
            echo json_encode(array('status' => true, 'lado1' => $lado1, 'lado2' => $lado2, 'lado3' => $lado3, 'resultado' => "O triângulo é Equilátero"));
        } else {
            if ($lado1 == $lado2 || $lado2 == $lado3 || $lado3 == $lado1) {
                echo json_encode(array('status' => true, 'lado1' => $lado1, 'lado2' => $lado2, 'lado3' => $lado3, 'resultado' => "O triângulo é Isósceles"));
            } else {
                echo json_encode(array('status' => true, 'lado1' => $lado1, 'lado2' => $lado2, 'lado3' => $lado3, 'resultado' => "O triângulo é Escaleno"));
            }
        }
    }
});
Example #20
0
File: index.php Project: njh/njh.me
<?php

require_once __DIR__ . '/../vendor/autoload.php';
// Prepare app
$app = new Slim(array('negotiation.enabled' => true));
// Setup routes
$app->get('/', function () use($app) {
    $format = $app->respondTo('html', 'rdf', 'ttl', 'json', 'nt');
    switch ($format) {
        case 'html':
            return $app->redirect('http://www.aelius.com/njh/', 303);
        default:
            $rootUrl = $app->request()->getUrl() . $app->request()->getScriptName();
            return $app->redirect("{$rootUrl}/foaf.{$format}", 303);
    }
});
$app->get('/foaf:format', function () use($app) {
    $format = $app->respondTo('rdf', 'ttl', 'json', 'nt');
    $uri = $app->request()->getUrl() . $app->request()->getPath();
    $foaf = new EasyRdf_Graph($uri);
    $foaf->parseFile(__DIR__ . '/../data/foaf.ttl', 'turtle', $uri);
    $app->response()->body($foaf->serialise($format));
});
// Run app
$app->run();
Example #21
0
require_once 'init.php';
require_once BASE_DIR . '/vendor/Slim/Slim/Slim.php';
require_once BASE_DIR . '/vendor/Slim-Extras/Log Writers/TimestampLogFileWriter.php';
$app = new Slim(array('mode' => defined('PRODUCTION') ? 'production' : 'development', 'debug' => false, 'log.enabled' => true, 'log.writer' => new TimestampLogFileWriter(array('path' => BASE_DIR, 'name_format' => '\\s\\l\\i\\m\\_\\l\\o\\g'))));
$app->configureMode('development', function () use($app) {
    $app->config(array('debug' => true));
});
$app->configureMode('production', function () use($app) {
    error_reporting(0);
    $app->notFound(function () use($app) {
        $page = new ErrorController(404);
        $page->render();
    });
    $app->error(function (Exception $e) use($app) {
        $app->response()->status(500);
        if (!$app->request()->isAjax()) {
            $page = new ErrorController(500);
            $page->render();
        }
        $app->stop();
        if (file_exists(BASE_DIR . '/.gbemail')) {
            foreach (explode('\\n', file_get_contents(BASE_DIR . '/.gbemail')) as $email) {
                mail(trim($email), "GetchaBooks Error", get_error_message($e));
            }
        }
    });
});
$app->hook('slim.before', function () use($app) {
    global $referrers;
    $request = $app->request();
    define('BASE_URL', $request->getUrl() . $request->getRootUri() . '/');
Example #22
0
        $db = getConnection();
        $stmt = $db->prepare($sql);
        $stmt->execute();
        $req_data = $stmt->fetchAll(PDO::FETCH_OBJ);
        $db = null;
        $response = '{"require":' . json_encode($req_data) . '}';
    } catch (PDOException $e) {
        $response = '{"error":{"text":"' . $e->getMessage() . '"}}';
    }
    return $response;
}
/**
 * 插入一条数据
 */
$app->post('/require', function () use($app) {
    $req_data = $app->request()->post();
    $data = $req_data['require'];
    $data['require_add_time'] = date('Y-m-d H:i:s');
    $sql = buildSqlInsert('tb_require', $data);
    try {
        $db = getConnection();
        $stmt = $db->prepare($sql);
        $stmt->execute();
        $data['require_id'] = $db->lastInsertId();
        //插入tb_attribute表
        $att = array('att_require_id' => $data['require_id'], 'att_text' => $data['require_ads'], 'attr_type_id' => $data['require_type_id'], 'att_rank_id' => $data['require_rank_id'], 'att_is_parent' => 1);
        try {
            $sql2 = buildSqlInsert('tb_attribute', $att);
            $stmt = $db->prepare($sql2);
            $stmt->execute();
            $db = null;
Example #23
0
    $post_path = $dir . '/' . $post;
    // if the post doesn't exists, 404 redirect
    if (!file_exists($post_path)) {
        $blog->notFound();
    }
    // get the post's file contents
    $post_data = file_get_contents($post_path);
    // parse the file for its meta data
    $post_data = explode('--', $post_data);
    // move the meta data into its array, and decode the json data
    $post_meta_json = array_shift($post_data);
    $post_meta = json_decode($post_meta_json, true);
    // parse the markdown portion into HTML
    $post_html = $blog->config('md')->transformMarkdown($post_data[0]);
    // get information about the request to compose the full url
    $request = $blog->request();
    $headers = $request->headers();
    $resource_uri = $request->getResourceUri();
    // build the full url for disqus to use
    $full_url = $headers['SERVER_PORT'] == '443' ? 'https://' : 'http://';
    $full_url .= $headers['HOST'];
    $full_url .= $resource_uri;
    // build the final post object
    $post_result = array('title' => $post_meta['title'], 'date' => $post_meta['date'], 'tags' => $post_meta['tags'], 'desc' => $post_meta['desc'], 'html' => $post_html, 'disqusid' => strtotime($post_meta['date']), 'disqusurl' => $full_url);
    // render the post view
    $blog->render('post.html', array('post' => $post_result));
});
// tag view
$blog->get('/blog/tagged/:tag', function ($tag) use($blog, $getMarkdownPosts) {
    // get all the posts
    $posts = $getMarkdownPosts($blog->config('posts.path'));
Example #24
0
    if ($count) {
        Data::$data['posts'] = array(Data::$data['posts_all'][key(Data::$data['posts_all'])]);
    }
    if ($count > 1) {
        Data::$data['next_page'] = 1;
    }
    $app->render('index.php', Data::$data);
});
// Blog Admin Login
$app->get('/login', function () use($app) {
    $data['title'] = $app->config('title');
    $app->render('login.php', $data);
});
// Blog Admin Post
$app->post('/login', function () use($app) {
    $username = $app->request()->post('username');
    $password = $app->request()->post('password');
    if (authenticate($app, $username, $password)) {
        $_SESSION['logged_in'] = true;
        $app->redirect('/');
    }
    $app->redirect('/login');
});
// Create new blog post
$app->post('/new_post', function () use($app) {
    $title = $app->request()->post('title');
    $body = $app->request()->post('body');
    if ($title && $body) {
        if (new Post($title, $body)) {
            $app->redirect('/');
        } else {
Example #25
0
        if (strpos($key, 'X_') === 0 || in_array($key, $specialHeaders)) {
            $env_mock[$key] = $value;
        }
    }
}
$env_mock['PATH_INFO'] = $_REQUEST['route'];
$env_mock['slim.url_scheme'] = empty($_SERVER['HTTPS']) || $_SERVER['HTTPS'] === 'off' ? 'http' : 'https';
$rawInput = @file_get_contents('php://input');
if (!$rawInput) {
    $rawInput = '';
}
$env_mock['slim.input'] = $rawInput;
$env_mock['slim.errors'] = fopen('php://stderr', 'w');
Slim_Environment::mock($env_mock);
$we_betatext = new Slim();
// die Funktionen für die einzelnen Abfragetypen liegen in eigenen Dateien
$method = strtolower($we_betatext->request()->getMethod());
require BBT_restpath . '/actions/' . $method . '.php';
// Standard-Funktionen
function send_response($out)
{
    global $we_betatext;
    if ($out !== false) {
        $response = $we_betatext->response();
        $response['Content-Type'] = 'application/json';
        $response['Cache-Control'] = 'no-cache';
        echo json_encode($out);
    } else {
    }
}
$we_betatext->run();
Example #26
0
 /**
  * Test parses request body based on media-type only, disregarding
  * any extra content-type header parameters
  */
 public function testParsesRequestBodyWithMediaType()
 {
     Slim_Environment::mock(array('REQUEST_METHOD' => 'POST', 'CONTENT_TYPE' => 'application/json; charset=ISO-8859-4', 'CONENT_LENGTH' => 13, 'slim.input' => '{"foo":"bar"}'));
     $s = new Slim();
     $s->add(new Slim_Middleware_ContentTypes());
     $s->run();
     $body = $s->request()->getBody();
     $this->assertTrue(is_array($body));
     $this->assertEquals('bar', $body['foo']);
 }
Example #27
0
<?php

set_include_path(implode(PATH_SEPARATOR, array(realpath(dirname(__FILE__) . '/library'), get_include_path())));
require_once 'Slim/Slim.php';
require_once 'controller/ProdutosController.php';
$app = new Slim();
$pcontroller = new ProdutosController();
$app->get('/produtos', function () use($pcontroller) {
    echo json_encode($pcontroller->listarProdutos());
});
$app->post('/produtos', function () use($pcontroller, $app) {
    $produto = json_decode(file_get_contents("php://input"));
    echo json_encode($pcontroller->salvarProduto($produto));
});
$app->put('/produtos', function () use($pcontroller, $app) {
    $produto = $app->request()->put();
    unset($produto['$$hashKey']);
    echo json_encode($pcontroller->atualizarProduto($produto));
});
$app->delete('/produtos/:id', function ($id) use($pcontroller) {
    echo $pcontroller->removerProduto($id);
});
$app->run();
Example #28
0
 /**
  * Set ETag HTTP Response Header
  *
  * Set the etag header and stop if the conditional GET request matches. 
  * The `value` argument is a unique identifier for the current resource. 
  * The `type` argument indicates whether the etag should be used as a strong or
  * weak cache validator.
  *
  * When the current request includes an 'If-None-Match' header with
  * a matching etag, execution is immediately stopped. If the request
  * method is GET or HEAD, a '304 Not Modified' response is sent.
  *
  * @param 	string 						$value 	The etag value
  * @param 	string 						$type 	The type of etag to create; either "strong" or "weak"
  * @throws 	InvalidArgumentException 			If provided type is invalid
  */
 public static function etag($value, $type = 'strong')
 {
     //Ensure type is correct
     if (!in_array($type, array('strong', 'weak'))) {
         throw new InvalidArgumentException('Invalid Slim::etag type. Expected "strong" or "weak".');
     }
     //Set etag value
     $value = '"' . $value . '"';
     if ($type === 'weak') {
         $value = 'W/' . $value;
     }
     Slim::response()->header('ETag', $value);
     //Check conditional GET
     if ($etagsHeader = Slim::request()->header('IF_NONE_MATCH')) {
         $etags = preg_split('@\\s*,\\s*@', $etagsHeader);
         if (in_array($value, $etags) || in_array('*', $etags)) {
             Slim::raise(304);
         }
     }
 }
Example #29
0
<?php

require "includes/index.php";
require_once "Slim/Slim.php";
$data = new Slim();
$data->get('/books/search', function () use($data) {
    $query = $data->request()->params('name');
    findByName($query);
});
$data->get('/books', 'getBooks');
$data->get('/books/:id', 'getBook');
//$data->get('/books/search:query', 'findByName');
$data->post('/books', 'addBook');
$data->put('/books/:id', 'updateBook');
$data->delete('/books/:id', 'deleteBook');
$data->run();
function getBooks()
{
    $sql = "select * FROM books ORDER BY id DESC";
    try {
        $db = getConnection();
        $stmt = $db->query($sql);
        $books = $stmt->fetchAll(PDO::FETCH_OBJ);
        $db = null;
        echo json_encode($books);
    } catch (PDOException $e) {
        echo '{"error":{"text":' . $e->getMessage() . '}}';
    }
}
function getBook($id)
{
Example #30
0
    //$app -> render("apiError.html");
});
/**
 * REST Methods
 */
$app->get('/teacher/', function () use($teacherModel) {
    $result = $teacherModel->get();
    echo json_encode($result);
});
$app->get('/course/', function () use($courseModel) {
    $result = $courseModel->get();
    echo json_encode($result);
});
$app->get('/teacherByCourse/:id/', function ($id) use($teacherModel) {
    $result = $teacherModel->getByCourseId($id);
    echo json_encode($result);
});
$app->post("/followup/", function () use($gamifiedModel, $app) {
    $request = array();
    parse_str($app->request()->getBody(), $request);
    $gamifiedModel->create($request["gamified"], $request["feedbackId"], $request["studentId"]);
});
$app->post("/link/", function () use($app, $authentication, $feedback) {
    if ($authentication->checkLogin()) {
        $request = json_decode($app->request()->getBody(), true);
        $feedback->linkTeachers($request["courseId"], array($request["teacherId"]));
    } else {
        echo json_encode(array("error" => "Not priviliged"));
    }
});
$app->run();