Example #1
0
 /**
  * Call
  * @param   array $env
  * @return  array[status, header, body]
  */
 public function call(&$env)
 {
     $env['slim.flash'] = $this;
     list($status, $header, $body) = $this->app->call($env);
     $this->save();
     return array($status, $header, $body);
 }
Example #2
0
 /**
  * Generic routes handler
  * @param  String $method Http method, e.g. GET, POST
  * @param  String $url    method url
  * @param  String $action action to perform
  * @return [type]         [description]
  */
 private function _call($method, $url, $action)
 {
     //return $this->app->$method($url, function () use ($action) {
     return $this->app->map($url, function () use($action) {
         $action = explode('@', $action);
         $modelClass = $action[0] . 'Model';
         $modelClassFile = ROOT . DS . APP_DIR . DS . 'Model' . DS . $modelClass . '.php';
         $model = NULL;
         if (file_exists($modelClassFile)) {
             require $modelClassFile;
             $model = new $modelClass($this->app);
         }
         $controllerClass = $action[0] . 'Controller';
         $controllerClassFile = ROOT . DS . APP_DIR . DS . 'Controller' . DS . $controllerClass . '.php';
         // TODO: check if file exists. Throw exception if it doesn't
         require $controllerClassFile;
         $method = $action[1];
         $controller = new $controllerClass($this->app, $model);
         // call controller
         call_user_func_array([$controller, $method], func_get_args());
         // Render view if no redirection has been set
         if ($this->app->response->getStatus() !== 302) {
             call_user_func_array([$controller, 'renderer'], [$action[0], $method]);
         }
     })->via($method);
     //return $this->app;
 }
Example #3
0
 /**
  * Call
  * @param   array $env
  * @return  array[status, header, body]
  */
 public function call(&$env)
 {
     if (isset($env['CONTENT_TYPE'])) {
         $env['slim.input_original'] = $env['slim.input'];
         $env['slim.input'] = $this->parse($env['slim.input'], $env['CONTENT_TYPE']);
     }
     return $this->app->call($env);
 }
Example #4
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 #5
0
 /**
  * @param string $repositoryName
  * @param string $packageName
  * @return \Composer\Package\PackageInterface
  */
 public function getPackage($repositoryName, $packageName)
 {
     $repository = $this->getRepository($repositoryName);
     $packages = $repository->findPackages($packageName);
     if (!$packages) {
         $this->app->redirect(ROOTURL . '/' . $repositoryName);
     }
     return array_shift($packages);
 }
Example #6
0
 /**
  * Call
  * @param array $env
  * @return array[status, header, body]
  */
 public function call(&$env)
 {
     try {
         return $this->app->call($env);
     } catch (Exception $e) {
         $env['slim.log']->error($e);
         $response = new Slim_Http_Response($this->renderBody($env, $e), 500);
         return $response->finalize();
     }
 }
Example #7
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 #8
0
 /**
  * Test middleware returns diagnostic screen for error response
  */
 public function testReturnsDiagnosticsForErrorResponse()
 {
     Slim_Environment::mock(array('SCRIPT_NAME' => '/index.php', 'PATH_INFO' => '/foo'));
     $app = new Slim(array('log.enabled' => false));
     $app->get('/foo', function () {
         throw new Exception('Test Message', 100);
     });
     $mw = new Slim_Middleware_PrettyExceptions();
     $mw->setApplication($app);
     $mw->setNextMiddleware($app);
     $mw->call();
     $this->assertEquals(1, preg_match('@Slim Application Error@', $app->response()->body()));
     $this->assertEquals(500, $app->response()->status());
 }
function updateIcon()
{
    $request = Slim::getInstance()->request();
    $body = $request->getBody();
    $body = json_decode($body);
    unset($body->created_date);
    if (!empty($body->image)) {
        file_put_contents('./icon_images/' . $body->image->filename, base64_decode($body->image->base64));
        $body->image = $body->image->filename;
    } else {
        unset($body->image);
    }
    $id = $body->id;
    unset($body->image_url);
    if (isset($body->imagee)) {
        unset($body->imagee);
    }
    if (isset($body->id)) {
        unset($body->id);
    }
    $allinfo['save_data'] = $body;
    $coupon_details = edit(json_encode($allinfo), 'icon', $id);
    if (!empty($coupon_details)) {
        $result = '{"type":"success","message":"Changed Succesfully"}';
    } else {
        $result = '{"type":"error","message":"Not Changed"}';
    }
    echo $result;
}
Example #10
0
function authenticate()
{
    $app = Slim::getInstance();
    if (!App::user()) {
        $app->redirect("/connect/");
    }
}
function CustomerAction()
{
    $request = Slim::getInstance()->request();
    $customer = json_decode($request->getBody());
    //echo '{"users": ' . json_encode($user) . '}';exit;
    $token = $customer->access_token;
    //echo '{"error":{"text":"'.$token.'"}}'; exit;
    if ($customer->access_token != "") {
        $status_token = validate_token($customer->access_token);
        //echo '{"error":{"text":"'.$status_token.'"}}'; exit;
        if ($status_token == 'valid') {
            $sql = "INSERT INTO user_profile (firstname, lastname) VALUES ('" . $customer->first_name . "', '" . $customer->last_name . "' )";
            $db_host = "127.0.0.1";
            $db_user = "******";
            $db_pass = "";
            $db_name = "myavazone_db";
            $db = new DB();
            $db->connect($db_host, $db_user, '', false, false, $db_name, 'tbl_');
            $res_q = $db->query($sql);
            echo '{"apidata": "User Added Sucessfully."}';
            exit;
            break;
            //echo '{"error":{"text":'.mc_encrypt($user->password,$user->key).'}}';
            //echo '{"error":{"text":"Token is valid"}}';
        } else {
            echo '{"error":{"text":"Token is not valid"}}';
        }
    } else {
        echo '{"error":{"text":"Token is NULL"}}';
    }
    /*$user_details=array(
    		'password_hash'	=>	mc_encrypt('admin@123','d0a7e7997b6d5fcd55f4b5c32611b87cd923e88837b63bf2941ef819dc8ca282')
    	);*/
}
Example #12
0
function updatePerson($id)
{
    $request = Slim::getInstance()->request();
    $data = json_decode($request->getBody());
    $sql = "UPDATE people SET \n\t\t\t\temail=:email,\n\t\t\t\tfname=:fname,\n\t\t\t\tlname=:lname,\n\t\t\t\tclientId=:clientId,\n\t\t\t\tstatus=:status,\n\t\t\t\tphone=:phone,\n\t\t\t\tnotes=:notes\n\t\t\t\tWHERE id=:id";
    try {
        $db = getConnection();
        $stmt = $db->prepare($sql);
        $stmt->bindParam("email", $data->email);
        $stmt->bindParam("fname", $data->fname);
        $stmt->bindParam("lname", $data->lname);
        $stmt->bindParam("email", $data->email);
        $stmt->bindParam("email", $data->email);
        $stmt->bindParam("clientId", $data->clientId);
        $stmt->bindParam("status", $data->status);
        $stmt->bindParam("phone", $data->phone);
        $stmt->bindParam("notes", $data->notes);
        $stmt->bindParam("id", $id);
        $stmt->execute();
        $db = null;
        echo json_encode($data);
    } catch (PDOException $e) {
        echo '{"error":{"text":' . $e->getMessage() . '}}';
    }
}
 public function save()
 {
     GUMP::add_validator("unique", function ($field, $input, $param = NULL) {
         $checkExistingUser = R::findOne('user', 'user=?', array($input));
         if ($checkExistingUser == NULL) {
             return FALSE;
         } else {
             return TRUE;
         }
     });
     GUMP::add_validator("strong", function ($field, $input, $param = NULL) {
         return checkPasswordStrength($input);
     });
     $rules = array('reseller_username' => 'required|alpha_numeric|max_len,10|min_len,6|unique', 'reseller_password' => 'required|max_len,10|min_len,7|strong');
     $filters = array('reseller_username' => 'trim|sanitize_string', 'reseller_password' => 'trim|sanitize_string|md5');
     $app = Slim::getInstance();
     $post = $app->request()->post();
     // $app - Slim main app instance
     $postValues = $gump->filter($post, $filters);
     $validated = $gump->validate($gump->filter($postValues, $filters), $rules);
     if ($validated === TRUE) {
         $createUser = R::dispense('user');
         $createUser->user = $postValues['reseller_username'];
         $createUser->user = $postValues['reseller_password'];
     } else {
         $this->setError($gump->get_readable_errors(true));
     }
     if ($this->getError() == "") {
         $this->fails = FALSE;
     } else {
         $this->fails = TRUE;
     }
 }
Example #14
0
function _update($collection, $id)
{
    $document = json_decode(Slim::getInstance()->request()->getBody(), true);
    $data = MongoDB::mongoUpdate(MONGO_HOST, MONGO_DB, $collection, $id, $document);
    $app->response()->header('Content-Type', 'application/json');
    echo json_encode($data);
}
 public function __construct()
 {
     parent::__construct(array('templates.path' => TEMPLATE_PATH, 'view' => new RainTplView()));
     $this->container->singleton('mysuperclass', function ($container) {
         return new MySuperClass();
     });
 }
 /**
  * Test middleware overrides response content type to html
  */
 public function testResponseContentTypeIsOverriddenToHtml()
 {
     Slim_Environment::mock(array('SCRIPT_NAME' => '/index.php', 'PATH_INFO' => '/foo'));
     $app = new Slim(array('log.enabled' => false));
     $app->get('/foo', function () use($app) {
         $app->contentType('application/json;charset=utf-8');
         //<-- set content type to something else
         throw new Exception('Test Message', 100);
     });
     $mw = new Slim_Middleware_PrettyExceptions();
     $mw->setApplication($app);
     $mw->setNextMiddleware($app);
     $mw->call();
     $response = $app->response();
     $this->assertEquals('text/html', $response['Content-Type']);
 }
Example #17
0
function deleteFriendship()
{
    global $friendTable, $userTable;
    /* verifica se existe alguma informacao no corpo da mensagem */
    $request = Slim::getInstance()->request();
    $json = readRequestBody($request);
    if (!$json) {
        $response["status"] = 0;
        echo json_encode($response);
        return;
    }
    /* lendo dados do json */
    $appID = $json->appID;
    $crypt_data = $json->data;
    $iv = $json->iv;
    $json = json_decode(decrypt_data($appID, $crypt_data, $iv));
    $id1 = $json->idusuario_a;
    $id2 = $json->idusuario_b;
    $response["status"] = 1;
    $dbh = getConnection();
    $sql = "DELETE FROM {$friendTable} where (idusuario_a = :id1 and\n\t\t\t\tidusuario_b = :id2) or (idusuario_a = :id2 and\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tidusuario_b = :id1)";
    $stmt = $dbh->prepare($sql);
    $stmt->bindParam(":id1", $id1);
    $stmt->bindParam(":id2", $id2);
    $stmt->execute();
    closeConnection($dbh);
    $json = json_encode($response);
    $data = encrypt_data($appID, $json);
    echo json_encode($data);
}
function youtube_oauth()
{
    global $config;
    $app = Slim::getInstance();
    $code = $app->request()->get("code");
    if ($code) {
        //initial
        $access_params = array("code" => $code, "client_id" => $config["youtube_client_id"], "client_secret" => $config["youtube_client_secret"], "redirect_uri" => $config["youtube_oauth_callback"], "grant_type" => "authorization_code");
        $ch = curl_init("https://accounts.google.com/o/oauth2/token");
        curl_setopt($ch, CURLOPT_POST, count($access_params));
        curl_setopt($ch, CURLOPT_POSTFIELDS, $access_params);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $json_string_data = curl_exec($ch);
        curl_close($ch);
        if ($json_string_data) {
            $auth_data = json_decode($json_string_data, true);
            $_SESSION["youtube_auth"] = $auth_data;
            dump($auth_data);
            //make a call to get the author data
            //log everything in the database
        } else {
            $app->redirect('/');
        }
    } else {
        $app->redirect('/');
    }
}
Example #19
0
 /**
  * Returns the layout for this view. This will be either
  * the 'layout' data value, the applications 'layout' configuration
  * value, or 'layout.php'.
  *
  * @param array $data Any additonal data to be passed to the template.
  *
  * @return string|null
  */
 public function getLayout($data = null)
 {
     $layout = null;
     // 1) Check the passed in data
     if (is_array($data) && array_key_exists(self::LAYOUT_KEY, $data)) {
         $layout = $data[self::LAYOUT_KEY];
         unset($data[self::LAYOUT_KEY]);
     }
     // 2) Check the data on the View
     if ($this->has(self::LAYOUT_KEY)) {
         $layout = $this->get(self::LAYOUT_KEY);
         $this->remove(self::LAYOUT_KEY);
     }
     // 3) Check the Slim configuration
     if (is_null($layout)) {
         $app = Slim::getInstance();
         if (isset($app)) {
             $layout = $app->config(self::LAYOUT_KEY);
         }
     }
     // 4) Use the default layout
     if (is_null($layout)) {
         $layout = self::DEFAULT_LAYOUT;
     }
     return $layout;
 }
Example #20
0
 public function fileFsPost()
 {
     LFileTest::createTests();
     $this->app->response->setBody(LFileTest::$Tester->gibSituationsdaten('fileFsPost'));
     $this->app->response->setStatus(201);
     $this->app->stop();
 }
Example #21
0
 /**
  * Render view for specific action
  * @param  string $dir  directory name that contains the view files
  * @param  string $view view file
  * @return void
  */
 public function renderView($dir, $view)
 {
     $templatePath = $this->app->config->get('app.settings.renderer.template_path');
     $templateExt = $this->app->config->get('app.settings.renderer.template_ext');
     $file = $templatePath . DS . $dir . DS . $view . $templateExt;
     ob_start();
     if (isset($this->viewData)) {
         extract($this->viewData);
     }
     require $file;
     $content = ob_get_clean();
     // Store slim app to pass it to the view
     $app = $this->app;
     // Append data to view
     $this->app->view->appendData(compact('app', 'content'));
     $this->app->render($this->layout);
 }
Example #22
0
function addQuote()
{
    $request = Slim::getInstance()->request();
    $data = json_decode($request->getBody());
    $quoteCrud = new QuotesCrud();
    $results = $quoteCrud->post($data);
    echo json_encode($results, JSON_NUMERIC_CHECK);
}
Example #23
0
function authuser($role = 'member')
{
    $user = User::fetchFromDatabaseSomehow();
    if ($user->belongsToRole($role) === false) {
        Slim::flash('error', 'Login required');
        Slim::redirect('/login');
    }
}
Example #24
0
 /**
  * Constructor
  *
  * Initialize things.
  *
  */
 function __construct()
 {
     if (null == self::$_appInstance) {
         self::$_appInstance = Slim::getInstance();
     }
     Doctrine_Core::loadModels(MODELS_PATH);
     DoctrineAdapter::getInstance();
 }
Example #25
0
function _update($db, $collection, $id)
{
    $document = json_decode(Slim::getInstance()->request()->getBody(), true);
    $data = mongoUpdate(MONGO_HOST, $db, $collection, $id, $document);
    header("Content-Type: application/json");
    echo json_encode($data);
    exit;
}
Example #26
0
 /**
  * Returns whether the component is installed for the given course
  *
  * Called when this component receives an HTTP GET request to
  * /link/exists/course/$courseid(/).
  *
  * @param int $courseid A course id.
  */
 public function getExistsCourse($courseid)
 {
     $result = Request::routeRequest('GET', '/process/course/' . $courseid . '/component/' . $this->_conf->getId(), $this->app->request->headers->all(), '', $this->_getProcess, 'process');
     if (isset($result['status']) && $result['status'] >= 200 && $result['status'] <= 299 && isset($result['content']) && $this->_conf !== null && $this->_conf->getId() !== null) {
         $this->app->response->setStatus(200);
         $this->app->stop();
     }
     $this->app->response->setStatus(409);
 }
Example #27
0
 /**
  * Constructor
  *
  * Initialize things.
  *
  */
 function __construct()
 {
     if (null == self::$_appInstance) {
         self::$_appInstance = Slim::getInstance();
     }
     if (null == self::$_dbInstance) {
         self::$_dbInstance = PDOAdpter::getInstance();
     }
 }
Example #28
0
 function show_result($data, $template = 'home.html', $error_code = null)
 {
     $app = Slim::getInstance();
     if ($app->request()->isAjax()) {
         echo json_encode($data);
     } else {
         $app->render($template, $data, $error_code);
     }
 }
Example #29
0
/**
* A function to add a class
*/
function addScanResults()
{
    $results = json_decode(Slim::getInstance()->request()->post('scanResults'), true);
    try {
        $db = getConnection();
        $select = "SELECT idVertex FROM Vertices WHERE X=:coordinateX and Y=:coordinateY";
        $coordinate = $results['Coordinates'];
        $stmt = $db->prepare($select);
        $stmt->bindParam("coordinateX", $coordinate[0]);
        $stmt->bindParam("coordinateY", $coordinate[1]);
        $stmt->execute();
        $vertexId = $stmt->fetchAll(PDO::FETCH_OBJ);
        if (empty($vertexId)) {
            $insertVertex = "INSERT INTO Vertices(X, Y) VALUE(:coordinateX, :coordinateY)";
            $stmt = $db->prepare($insertVertex);
            $stmt->bindParam("coordinateX", $coordinate[0]);
            $stmt->bindParam("coordinateY", $coordinate[1]);
            $stmt->execute();
            $vertexId = $db->lastInsertId();
        } else {
            $vertexId = $vertexId[0]->idVertex;
        }
        $insertDirection = "INSERT INTO DirectionTime(direction) VALUE(:direction)";
        $stmt = $db->prepare($insertDirection);
        $stmt->bindParam("direction", $results['Direction']);
        $stmt->execute();
        $directionId = $db->lastInsertId();
        foreach ($results['Tests'] as $test) {
            foreach ($test as $accesspoint) {
                $selectMac = "SELECT idMac FROM Mac WHERE macAddress=:address";
                $stmt = $db->prepare($selectMac);
                $stmt->bindParam("address", $accesspoint['AccessPoint']);
                $stmt->execute();
                $macId = $stmt->fetchAll(PDO::FETCH_OBJ);
                if (empty($macId)) {
                    $insertMac = "INSERT INTO Mac(macAddress) VALUE(:address)";
                    $stmt = $db->prepare($insertMac);
                    $stmt->bindParam("address", $accesspoint['AccessPoint']);
                    $stmt->execute();
                    $macId = $db->lastInsertId();
                } else {
                    $macId = $macId[0]->idMac;
                }
                $finalInsert = "INSERT INTO Data(idVertex, idMac, idDirectionTime, strength) VALUE(:vertex, :mac, :direction, :strength)";
                $stmt = $db->prepare($finalInsert);
                $stmt->bindParam("vertex", $vertexId);
                $stmt->bindParam("mac", $macId);
                $stmt->bindParam("direction", $directionId);
                $stmt->bindParam("strength", $accesspoint['SignalStrength']);
                $stmt->execute();
            }
        }
        $db = null;
    } catch (PDOException $e) {
        echo '{"error":{"text":' . $e->getMessage() . '}}';
    }
}
Example #30
-1
 /**
  * REST actions
  *
  * This function contains the REST actions with the assignments to
  * the functions.
  */
 public function __construct()
 {
     // runs the CConfig
     $com = new CConfig(LFile::$_baseDir, dirname(__FILE__));
     // runs the LFile
     if ($com->used()) {
         return;
     }
     $conf = $com->loadConfig();
     $this->_conf = $conf;
     $this->_fs = CConfig::getLinks($this->_conf->getLinks(), 'file');
     $this->_db = CConfig::getLinks($this->_conf->getLinks(), 'fileDb');
     $this->_app = new \Slim\Slim(array('debug' => true));
     $this->_app->response->setStatus(404);
     $this->_app->response->headers->set('Content-Type', 'application/json');
     // POST File
     $this->_app->post('/' . LFile::$_baseDir . '(/)', array($this, 'postFile'));
     /*// POST PathFile
       $this->_app->post( 
                         '/' . LFile::$_baseDir . '/:path(/)',
                         array( 
                               $this,
                               'postPathFile'
                               )
                         );*/
     // DELETE File
     $this->_app->delete('/' . LFile::$_baseDir . '/:fileid', array($this, 'deleteFile'));
     // run Slim
     $this->_app->run();
 }