public function setUp()
 {
     $redbean = new RedBean_Facade();
     $redbean->setup('sqlite::memory:');
     $tables = array('client' => 'clients', 'access_token' => 'accesstokens', 'code' => 'codes');
     $this->storage = new \ebussola\oauth\redbean\GrantCode($redbean, $tables);
     $client_bean = $redbean->dispense($tables['client']);
     $client = new \ebussola\oauth\client\Client($client_bean);
     $client->redirect_uris = array();
     $client->client_secret = 'xpto';
     $redbean->store($client->getBean());
     $this->oauth2 = new \OAuth2\OAuth2($this->storage);
 }
Example #2
0
function createUser()
{
    $success = false;
    RedBean_Facade::setup('mysql:host=localhost;
			dbname=didapi', 'root', '');
    //$user = R::find('user', ' username = ?', array( 'admin') );
    //	if (!isset($user))
    //	{
    $user = RedBean_Facade::dispense('user');
    $user->username = '******';
    $user->name = 'Admin';
    $user->firstname = 'Admin';
    $user->is_admin = true;
    $user->password = hash('sha256', 'Di8Ap1');
    $id = RedBean_Facade::store($user);
    if ($id != null) {
        $success = true;
    }
    //	}
    //	else
    //	{
    //		$success = false;
    //	}
    return $success;
}
Example #3
0
 /**
  * Tries to find content that matches the input query
  * @param string $query
  */
 public function find($query)
 {
     $q = implode('%', explode(' ', $query));
     $sql = 'SELECT content.* FROM content JOIN idiom ON content.idiom_id = idiom.id
         WHERE idiom.code = ? AND content.publish = 1 
             AND (
                 content.keywords like (?)
                 OR content.alias like (?) 
                 OR content.title like (?)
                 OR content.description like (?)
                 OR content.intro like (?)
                 OR content.html like (?)
                 )
         ORDER BY visits DESC';
     // Prepare values and run query
     $q = "%{$q}%";
     $rows = R::getAll($sql, array(BootWiki::getIdiom(), $q, $q, $q, $q, $q, $q));
     $results = R::convertToBeans('content', $rows);
     if (!empty($results)) {
         foreach ($results as $item) {
             $content = new Content($item->alias);
             $content->importBean($item);
             $this->items[] = $content;
         }
     }
 }
 /**
  * Tests the facade-only dispenseAll method.
  * 
  * @return void
  */
 public function testDispenseAll()
 {
     list($book, $page) = RedBean_Facade::dispenseAll('book,page');
     asrt($book instanceof RedBean_OODBBean, true);
     asrt($page instanceof RedBean_OODBBean, true);
     asrt($book->getMeta('type'), 'book');
     asrt($page->getMeta('type'), 'page');
     list($book, $page, $texts, $mark) = R::dispenseAll('book,page,text*2,mark');
     asrt($book instanceof RedBean_OODBBean, true);
     asrt($page instanceof RedBean_OODBBean, true);
     asrt(is_array($texts), true);
     asrt($mark instanceof RedBean_OODBBean, true);
     asrt($book->getMeta('type'), 'book');
     asrt($page->getMeta('type'), 'page');
     asrt($mark->getMeta('type'), 'mark');
     asrt($texts[0]->getMeta('type'), 'text');
     asrt($texts[1]->getMeta('type'), 'text');
     list($eggs, $milk, $butter) = R::dispenseAll('eggs*3,milk*1,butter*9');
     asrt(count($eggs), 3);
     asrt($milk instanceof RedBean_OODBBean, true);
     asrt(count($butter), 9);
     list($beer) = R::dispenseAll('beer*0');
     asrt(is_array($beer), true);
     asrt(count($beer), 0);
 }
Example #5
0
 static function disconnect()
 {
     if (!self::$initialized) {
         return true;
     }
     self::$isConnected = false;
     \RedBean_Facade::close();
 }
Example #6
0
 public function update()
 {
     if (!$this->createdAt) {
         $this->createdAt = R::isoDateTime();
     }
     if ($this->bean->getMeta("tainted")) {
         $this->updatedAt = R::isoDateTime();
     }
 }
Example #7
0
 /**
  * Helper to load all idioms
  */
 public function loadIdioms()
 {
     $idioms = R::find('idiom');
     foreach ($idioms as $item) {
         $idiom = new Idiom();
         $idiom->importBean($item);
         $this->idioms[] = $idiom;
     }
 }
Example #8
0
 public function saveAll($data)
 {
     $collection = array();
     foreach ($data as $index => $row) {
         $collection[$index] = R::dispense($this->name);
         foreach ($row as $name => $value) {
             $collection[$index]->{$name} = $value;
         }
     }
     R::storeAll($collection);
 }
Example #9
0
 /**
  * Store the supplied access token values to storage.
  *
  * We need to store access token data as we create and verify tokens.
  *
  * @param string        $oauth_token
  * The access token string to be stored.
  * @param IOAuth2Client $client
  * The client associated with this refresh token.
  * @param mixed         $data
  * Application data associated with the refresh token, such as a User object.
  * @param int           $expires
  * The timestamp when the refresh token will expire.
  * @param string        $scope
  * (optional) Scopes to be stored in space-separated string.
  *
  * @ingroup oauth2_section_4
  */
 public function createAccessToken($oauth_token, IOAuth2Client $client, $data, $expires, $scope = null)
 {
     $access_token_bean = $this->redbean->dispense($this->tables['access_token']);
     $access_token = new AccessToken($access_token_bean);
     $access_token->token = $oauth_token;
     $access_token->client_id = $client->getPublicId();
     $access_token->data = $data;
     $access_token->expires_in = $expires;
     $access_token->has_expired = false;
     $access_token->scope = $scope;
     $this->redbean->store($access_token->getBean());
 }
 public function testMarkAuthCodeAsUsed()
 {
     $client_bean = $this->redbean->dispense($this->tables['code']);
     $client = new \ebussola\oauth\client\Client($client_bean);
     $code_str = md5(uniqid(time()));
     $data = [];
     $redirect_uri = 'http://google.com';
     $expires = time() + 3600;
     $this->redbean_storage->createAuthCode($code_str, $client, $data, $redirect_uri, $expires);
     $this->redbean_storage->markAuthCodeAsUsed($code_str);
     $results = $this->redbean->findAll($this->tables['code'], 'code = ?', [$code_str]);
     $this->assertCount(0, $results);
 }
Example #11
0
 /**
  * Fetch all allowed operatations for user
  *
  * @return array
  */
 protected function getData()
 {
     // Get results from cache if they exist
     $this->manager->getCache() && ($rows = $this->manager->getCache()->get($this->cacheKey . $this->identity));
     if (isset($rows) && is_array($rows) && count($rows) > 0) {
         return $this->parse(static::ITEM_CLASS, $rows);
     }
     // Nothing found in cache, or cached array is empty, lookup from db
     $rows = R::getAll("\n          SELECT\n            DISTINCT `role`.`name` AS item_name,\n            `role`.`id` AS item_id,\n            `role`.`description` AS item_desc\n          FROM `role`\n          JOIN `role_user` ON (`role_user`.`role_id` = `role`.`id`)\n          WHERE `role_user`.`user_id` = :id\n          ORDER BY item_name ASC\n        ", [':id' => $this->identity]);
     // Save to cache
     $this->manager->getCache() && $this->manager->getCache()->set($this->cacheKey . $this->identity, $rows, $this->cacheTtl);
     return $this->parse(static::ITEM_CLASS, $rows);
 }
Example #12
0
 public static function defaultLayer()
 {
     $layer = R::findOne('layer', 'identifier = ?', array('justmapit'));
     if (!$layer) {
         $layer = R::dispense('user');
         $layer->identifier = 'justmapit';
         $layer->creator = "admin";
         $layer->title = "testing";
         $layer->description = 'This is the base layer for Just Map It add any points of interest';
         $layer->security = JMIAuthenticationType::ANONYMOUS;
         R::store($layer);
     }
     return $layer;
 }
Example #13
0
function loginUser()
{
    $success = false;
    RedBean_Facade::setup('mysql:host=' . Database::HOST . ';dbname=' . Database::NAME, Database::USERNAME, Database::PASSWORD);
    //echo hash('sha256', $_POST['password']);
    $user = RedBean_Facade::findOne('user', ' username = :username AND password = :password LIMIT 1', array(':username' => $_POST['username'], ':password' => hash('sha256', $_POST['password'])));
    if (isset($user)) {
        $currentUser = new User($user["username"], $user["firstname"], $user["name"], $user["is_admin"], $user["id"]);
        $_SESSION['username'] = $user["username"];
        $_SESSION['user_id'] = $user["id"];
        $_SESSION['name'] = $user["name"];
        $_SESSION['firstname'] = $user["firstname"];
        $_SESSION['is_admin'] = $user["is_admin"];
        $success = true;
    }
    return $success;
}
Example #14
0
 public function __construct($routes = null)
 {
     $appConfig = array('templates.path' => realpath('../views'), 'mode' => isset($_SERVER['PLIERS_ENV']) ? $_SERVER['PLIERS_ENV'] : 'development');
     if ($appConfig['mode'] === 'development') {
         $appConfig['debug'] = true;
     } else {
         $appConfig['debug'] = false;
     }
     parent::__construct($appConfig);
     if ($routes !== null) {
         self::$initialRoutes = $routes;
     }
     $this->addRoutes();
     $this->setupConfig();
     // Set up RedBean
     R::setup($this->conf->db->dsn, $this->conf->db->username, $this->conf->db->password);
     $this->app = self::getInstance();
     $this->utils = new Utils();
 }
Example #15
0
 public static function setupRedBeans()
 {
     $config = Config::get();
     if (!isset($config['db']['host'])) {
         throw new Exception('Config[db][host] not set. Check api.conf in project folder.');
     }
     if (!isset($config['db']['db'])) {
         throw new Exception('Config[db][db] not set. Check api.conf in project folder.');
     }
     if (!isset($config['db']['user'])) {
         throw new Exception('Config[db][user] not set. Check api.conf in project folder.');
     }
     if (!isset($config['db']['password'])) {
         throw new Exception('Config[db][password] not set. Check api.conf in project folder.');
     }
     R::setup('mysql:host=' . $config['db']['host'] . ';dbname=' . $config['db']['db'], $config['db']['user'], $config['db']['password'], true);
     R::exec('SET NAMES utf8mb4');
     R::freeze(true);
 }
Example #16
0
 /**
  * Test if we can dynamically extend the R-facade.
  * 
  * @return void
  */
 public function testDynamicPlugins()
 {
     testpack('Test dynamic plugins');
     //basic behaviour
     R::ext('makeTea', function () {
         return 'sorry cant do that!';
     });
     asrt(R::makeTea(), 'sorry cant do that!');
     //with parameters
     R::ext('multiply', function ($a, $b) {
         return $a * $b;
     });
     asrt(R::multiply(3, 4), 12);
     //can we call R inside?
     R::ext('singVersion', function () {
         return R::getVersion() . ' lalala !';
     });
     asrt(R::singVersion(), R::getVersion() . ' lalala !');
     //should also work with RedBean_Facade
     asrt(RedBean_Facade::singVersion(), R::getVersion() . ' lalala !');
     //test error handling
     try {
         R::ext('---', function () {
         });
         fail();
     } catch (RedBean_Exception $e) {
         asrt($e->getMessage(), 'Plugin name may only contain alphanumeric characters.');
     }
     try {
         R::__callStatic('---', function () {
         });
         fail();
     } catch (RedBean_Exception $e) {
         asrt($e->getMessage(), 'Plugin name may only contain alphanumeric characters.');
     }
     try {
         R::invalidMethod();
         fail();
     } catch (RedBean_Exception $e) {
         asrt($e->getMessage(), 'Plugin \'invalidMethod\' does not exist, add this plugin using: R::ext(\'invalidMethod\')');
     }
 }
Example #17
0
function API()
{
    $app = \Slim\Slim::getInstance();
    $app->view(new \JsonApiView());
    $app->add(new \JsonApiMiddleware());
    $app->response->headers->set('Content-Type', 'application/json');
    $app->response->headers->set('Access-Control-Allow-Methods', 'GET,HEAD,POST,PUT,DELETE,OPTIONS');
    $app->response->headers->set('Access-Control-Allow-Headers', 'Auth-Token,Content-Type');
    $app->response->headers->set('Access-Control-Allow-Credentials', 'true');
    $uri = array_values(array_filter(explode('/', $app->request->getResourceUri())));
    $package = R::findOne('managepackages', ' name = ?', array($uri[0]));
    if ($package) {
        $origin = $package->origin;
        if (!$origin) {
            $origin = 'http://localhost';
        }
    } else {
        $origin = 'http://localhost';
    }
    $app->response->headers->set("Access-Control-Allow-Origin", $origin);
}
Example #18
0
 public static function setup($dsn = null, $username = null, $password = null, $frozen = false)
 {
     parent::setup($dsn, $username, $password, $frozen);
     self::$x = new Rx_FindHelper();
 }
Example #19
0
 /**
  * Constructor.
  * Creates a new instance of the Resty BeanCan Server.
  * If no toolbox is provided the Resty BeanCan Server object will
  * try to obtain the toolbox currently used by the RedBeanPHP facade.
  * If you use only the R-methods and not the advanced objects this should be fine.
  *
  * @param RedBean_ToolBox $toolbox (optional)
  */
 public function __construct($toolbox = NULL)
 {
     if ($toolbox instanceof RedBean_ToolBox) {
         $this->toolbox = $toolbox;
         $this->oodb = $toolbox->getRedBean();
     } else {
         $this->toolbox = RedBean_Facade::getToolBox();
         $this->oodb = RedBean_Facade::getRedBean();
     }
 }
Example #20
0
 /**
  * Optional accessor for neat code.
  * Sets the database adapter you want to use.
  *
  * @param RedBean_OODB $redbean
  */
 public static function setRedBean(RedBean_OODB $redbean)
 {
     self::$redbean = $redbean;
 }
Example #21
0
            $bean = R::findOne('email', 'forwardto=:email AND time >= :time', array(':email' => $email, ':time' => time()));
            if ($bean) {
                $bean->time = time() + 120 * 60;
                R::store($bean);
                echo json_encode(array('success' => TRUE, 'email' => $bean->email . '@tempmail.ir'));
            } else {
                $rndmail = '';
                do {
                    $rndmail = generateRandomString(8);
                } while (R::count('email', 'email=:email AND time>=:time', array(':email' => $rndmail, ':time' => time())) > 0);
                $bean = R::dispense('email');
                $bean->email = $rndmail;
                $bean->forwardto = $email;
                $bean->time = time() + 120 * 60;
                $bean->ip = $ip;
                R::store($bean);
                echo json_encode(array('success' => TRUE, 'email' => $rndmail . '@tempmail.ir'));
            }
        }
    }
});
$app->run();
function check_email_address($email)
{
    if (!preg_match("/^[^@]{1,64}@[^@]{1,255}\$/", $email)) {
        return false;
    }
    // Split it into sections to make life easier
    $email_array = explode("@", $email);
    $local_array = explode(".", $email_array[0]);
    for ($i = 0; $i < sizeof($local_array); $i++) {
Example #22
0
 public function store($filePath, $shop, $imagePath)
 {
     $shopID = Shop::existsShop($shop)->id;
     $model = R::dispense('models');
     $model->name = 'new';
     $model->url = $filePath;
     $model->shop_id = $shopID;
     $model->image = $imagePath;
     return $id = R::store($model);
 }
Example #23
0
require_once __DIR__ . '/../.env.config.php';
require_once __DIR__ . '/../vendor/autoload.php';
use Silex\Application;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Silex\Provider\FormServiceProvider;
use RedBean_Facade as R;
// use Acme\MyClass;
// $myClass = new MyClass();
$app = new Application();
$env = getenv('APP_ENV') ?: 'prod';
define('APP_ENV', $env);
$app->register(new Igorw\Silex\ConfigServiceProvider(__DIR__ . "/../config/{$env}.json"));
// use $app['debug'], $app['db_name'], etc...
R::setup("mysql:host={$app['db_host']};dbname={$app['db_name']}", "{$app['db_user']}", "{$app['db_pass']}");
$app->register(new Silex\Provider\HttpCacheServiceProvider(), ['http_cache.cache_dir' => __DIR__ . '/http_cache/']);
$app->register(new Silex\Provider\TranslationServiceProvider(), array('locale' => 'de', 'translation.class_path' => __DIR__ . '/../locales', 'translator.messages' => array()));
$app->register(new Silex\Provider\ValidatorServiceProvider());
$app->register(new FormServiceProvider());
$app->register(new Silex\Provider\MonologServiceProvider(), array('monolog.logfile' => __DIR__ . '/logging.log'));
$app->register(new Silex\Provider\TwigServiceProvider(), array('twig.path' => __DIR__ . '/views', 'twig.options' => array('debug' => $app['debug'], 'strict_variables' => false, 'cache' => __DIR__ . '/twig_cache/', 'auto_reload' => $app['debug'])));
$app['twig']->addExtension(new Twig_Extension_Debug());
$addCacheMiddleware = function (Request $request, Response $response, Application $app) {
    return $response->setCache(['s_maxage' => 3600]);
};
// prepare structure for current request site
$app->before(function ($request, $app) {
});
// ------ ROUTING ------
// remove favicon spam
Example #24
0
 public static function load($post, RedBean_ToolBox $toolbox)
 {
     $writer = $toolbox->getWriter();
     if (isset($post["associations"])) {
         $associations = $post["associations"];
         unset($post["associations"]);
     }
     $can = $pairs = $sorted = array();
     foreach ($post as $key => $rawBean) {
         if (is_array($rawBean) && isset($rawBean["type"])) {
             $type = $rawBean["type"];
             unset($rawBean["type"]);
             $idfield = $writer->getIDField($type);
             if (isset($rawBean[$idfield])) {
                 $id = $rawBean[$idfield];
                 if ($id == 0 && count($rawBean) === 1) {
                     continue;
                 }
                 unset($rawBean[$idfield]);
                 $bean = RedBean_Facade::load($type, $id);
             } else {
                 $bean = RedBean_Facade::dispense($type);
             }
             foreach ($rawBean as $field => $value) {
                 if (!empty($value)) {
                     $bean->{$field} = $value;
                 } elseif (!self::$dontSetEmptyValues) {
                     $bean->{$field} = $value;
                 }
             }
             $can[$key] = $bean;
             if (!isset($sorted[$type])) {
                 $sorted[$type] = array();
             }
             $sorted[$type][] = $bean;
         }
     }
     if (isset($associations) && is_array($associations)) {
         foreach ($associations as $assoc) {
             foreach ($assoc as $info) {
                 if ($info == "0" || $info == "") {
                     continue;
                 }
                 $keys = explode("-", $info);
                 if (isset($can[$keys[0]])) {
                     $bean1 = $can[$keys[0]];
                 } else {
                     $loader = explode(":", $keys[0]);
                     $bean1 = RedBean_Facade::load($loader[0], $loader[1]);
                 }
                 $bean2 = $can[$keys[1]];
                 $pairs[] = array($bean1, $bean2);
             }
         }
     }
     return array("can" => $can, "pairs" => $pairs, "sorted" => $sorted);
 }
Example #25
0
<?php

require_once 'models/Answer.php';
use RedBean_Facade as R;
$payload = $app->request()->getBody();
$params = array('userid' => 'userid', 'questionid' => 'questionid', 'answer' => 'answer');
$payload = array_intersect_key($payload, $params);
if (empty($payload['questionid'])) {
    throw new \Exception('questionid is required!', 412);
}
$quetion = R::findOne('question', '`id` = ?', array($payload['questionid']));
if (!$quetion) {
    throw new \Exception('Question not found', 404);
}
$answer = new Answer($payload, $quetion);
$answer->validateAnswer();
R::exec('INSERT INTO `answer` (`userid`, `questionid`, `answer`) VALUES (:userid, :questionid, :answer)', array(':userid' => $answer->getValue('userid'), ':questionid' => $answer->getValue('questionid'), ':answer' => $answer->getValue('answer')));
$app->result = $answer->getValues();
Example #26
0
<?php

use RedBean_Facade as R;
if (empty($id)) {
    throw new \Exception('id is required', 412);
}
$q = R::findOne('question', '`id` = ?', array($id));
if (!$q) {
    throw new \Exception('Question not found', 404);
}
$q = $q->export();
$q['options'] = json_decode($q['options'], true);
$app->result = $q;
Example #27
0
 public function store()
 {
     date_default_timezone_set('Europe/Berlin');
     $date = date("Y-m-d h:i:s", time());
     $game = R::dispense('games');
     $game->player_id = self::getUserID($this->player);
     $game->enemy_id = self::getUserID($this->enemy);
     $game->date = $date;
     $game->goals = $this->goals;
     $game->goals_against = $this->goals_against;
     $game->points = self::getPoints($this->goals, $this->goals_against);
     R::store($game);
     $game = R::dispense('games');
     $game->player_id = self::getUserID($this->enemy);
     $game->enemy_id = self::getUserID($this->player);
     $game->date = $date;
     $game->goals = $this->goals_against;
     $game->goals_against = $this->goals;
     $game->points = self::getPoints($this->goals_against, $this->goals);
     return R::store($game);
 }
<?php

use RedBean_Facade as R;
$q = R::getAll('SELECT * FROM `question` ORDER BY `id`');
foreach ($q as $key => $val) {
    $q[$key]['options'] = json_decode($val['options'], true);
}
$app->result = $q;
Example #29
0
 /**
  * Support for RESTFul GET-requests.
  * Only supports very BASIC REST requests, for more functionality please use
  * the JSON-RPC 2 interface.
  * 
  * @param string $pathToResource RESTFul path to resource
  * 
  * @return string $json a JSON encoded response ready for sending to client
  */
 public function handleRESTGetRequest($pathToResource)
 {
     if (!is_string($pathToResource)) {
         return $this->resp(null, 0, -32099, 'IR');
     }
     $resourceInfo = explode('/', $pathToResource);
     $type = $resourceInfo[0];
     try {
         if (count($resourceInfo) < 2) {
             return $this->resp(RedBean_Facade::findAndExport($type));
         } else {
             $id = (int) $resourceInfo[1];
             return $this->resp(RedBean_Facade::load($type, $id)->export(), $id);
         }
     } catch (Exception $e) {
         return $this->resp(null, 0, -32099);
     }
 }
Example #30
0
 /**
  * Validates data (or post) to create a new account
  * @param array $post
  * @return boolean
  */
 public function validateCreate($post)
 {
     // Check security system
     if (!empty($post['reserved'])) {
         BootWiki::setMessage('Invalid submission. Are you a human?');
         return false;
     }
     // Check if username is in use
     $account = R::findOne('account', 'username = ?', array($post['username']));
     if (!empty($account)) {
         BootWiki::setMessage('Invalid username. Try another username');
         return false;
     }
     if (!$this->validatePassword($post)) {
         return false;
     }
     return true;
 }