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; }
/** * Creates a new account * @param array $post * @return boolean */ public function create($post) { // Validate create before continue $result = $this->validateCreate($post); if (!$result) { return false; } // Create account $account = R::dispense('account'); $account->username = $post['username']; $account->displayname = $post['displayname']; $account->profile = $post['profile']; $account->password = $post['password']; $this->importBean($account); // Encrypt password and save $passwd = BootWiki::encrypt($post['password']); $account->password = $passwd; R::store($account); // Send email to user $this->template_path = BootWiki::template('register_mail'); $message = (string) $this; BootWiki::sendMail($post['username'], 'BootWiki - Register', $message); // Return success return true; }
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); }
private static function SaveWithAttributes($post, $entityName) { $success = false; self::Connect(); $entity = RedBean_Facade::dispense($entityName); $entity = self::SetAttributes($entity, $post); $success = self::Store($entity); echo $success; self::Close(); return $success == true ? array('entity' => $entity, 'entity_id' => $id) : false; }
/** * 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 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); }
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); }
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; }
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); }
/** * Handles a JSON RPC 2 request to store a bean. * * @param string $id request ID, identification for request * @param string $beanType type of the bean you want to store * @param array $data data array * * @return string */ private function store($id, $beanType, $data) { if (!isset($data[0])) { return $this->resp(NULL, $id, self::C_JSONRPC2_INVALID_PARAMETERS, 'First param needs to be Bean Object'); } $data = $data[0]; if (!isset($data['id'])) { $bean = RedBean_Facade::dispense($beanType); } else { $bean = RedBean_Facade::load($beanType, $data['id']); } $bean->import($data); $rid = RedBean_Facade::store($bean); return $this->resp($rid, $id); }
$request = json_decode($app->request()->getBody()); if (!is_array($request) && !is_object($request)) { return $r->respond(400, 'MALFORMED DATA', true); } $request = (array) $request; $data = R::dispense($tableName); $request = $r->fireHookIfExists($package, $name, 'beforeInsert', $request); if ($request === false) { return $r->respond(403, 'FORBIDDEN:HOOK', true); } $requestData = $r->serialize(array($request))[0]; foreach ($requestData as $key => $value) { $data->{$key} = $value; } $id = R::store($data); $sm = R::dispense('syncmeta'); $sm->timestamp = date('Y-m-d H:i:s'); $sm->tableName = $tableName; $sm->type = 'insert'; $sm->row_id = $id; R::store($sm); $data = $r->unserialize(array($data->export()))[0]; if ($data) { $r->fireHookIfExists($package, $name, 'afterInsert', $data); return $r->respond(201, $data); } return $r->respond(500, 'ERROR WHILE INSERTING DATA', true); }); $app->put('/:package/:name/:id', 'API', 'CHECKTOKEN', 'RATELIMITER', function ($package, $name, $id) use($r, $app) { $tableName = $r->genTableName($package, $name); if (!$r->packageOK($package, 'update') && $tableName !== 'managepackages') {
echo json_encode(array('success' => FALSE, 'error' => 'INVALID')); } else { if (R::count('email', 'ip=:ip AND time>=:time', array(':ip' => $ip, ':time' => time() + 119 * 60)) >= 20) { echo json_encode(array('success' => FALSE, 'error' => 'LIMITATION')); } else { $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;
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); }
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); }
/** * Saves form data * @param array $post * @param array $upload_image */ public function savePost($post, $upload_image) { // Import fields (ugly i know) $fields = 'title,alias,publish,featured,date,description,keywords,author,intro,html,visits'; // Find record $bean = R::findOne('content', 'alias = ?', array($this->alias)); if (empty($bean)) { $bean = R::dispense('content'); } else { // Save last version $version = R::dispense('contentversion'); $version->import($bean->export(), $fields); $version->date = date('Y-m-d H:i:s'); $version->content = $bean; R::store($version); } // Import changes $bean->import($post, $fields); $bean->idiom = R::findOne('idiom', 'code = ?', array($post['idiom'])); $new_image = Image::upload($upload_image); if ($new_image) { $bean->image = $new_image; } // Save try { R::store($bean); $this->importBean($bean); } catch (Exception $e) { BootWiki::setMessage($e->getMessage()); } }
/** * Adds tags to a bean. * If $tagList is a comma separated list (string) of tags all tags will * be associated with the bean. * You may also pass an array instead of a string. * * @param RedBean_OODBBean $bean bean * @param mixed $tagList tags * * @return void */ public static function addTags(RedBean_OODBBean $bean, $tagList) { if ($tagList !== false && !is_array($tagList)) { $tags = explode(",", (string) $tagList); } else { $tags = $tagList; } if ($tagList === false) { return; } foreach ($tags as $tag) { $t = RedBean_Facade::findOne("tag", " title = ? ", array($tag)); if (!$t) { $t = RedBean_Facade::dispense("tag"); $t->title = $tag; RedBean_Facade::store($t); } RedBean_Facade::associate($bean, $t); } }
/** * Wiki install procedure * NOTE: after install, you should disable the route in the Slim application */ public static function install() { R::nuke(); // WARNING: THIS WILL DELETE YOUR DATA!!! //R::debug(true); $account = R::dispense('account'); $account->username = '******'; $account->password = self::encrypt('admin'); $account->displayname = 'Admin'; $account->profile = ''; R::store($account); // English content $idiom_en = R::dispense('idiom'); $idiom_en->code = 'en'; $idiom_en->name = 'English'; $idiom_en->flag_image = 'web/img/flags/United_Kingdom.png'; R::store($idiom_en); $content = new Content('Welcome to BootWiki!', '<p>A php Wiki with Twitter Bootstrap, RedBeanPHP and Slim Framework</p>'); $content->intro = '<p>A php Wiki with Twitter Bootstrap for your organization</p>'; $content->description = 'A php Wiki with Twitter Bootstrap for your organization'; $content->keywords = 'php wiki twitter bootstrap redbeanphp slim nice simple organizarion'; $content->idiom = new Idiom($idiom_en->code); $content->featured = 1; $content->author = $account->username; $bean = R::dispense('content'); R::store($content->exportToBean($bean)); $content = new Content('Wiki Features', '<ul><li>Add text and image content</li> <li>Most recent list</li> <li>Most popular list</li> <li>Keywords search</li> <li>WYSIHTML5 editor</li> <li>Multi-idiom</li> <li>Configure homepage featured content</li> <li>Versioning</li></ul>'); $content->intro = '<p>Look at the features that are essencial to a good and organized content.</p>'; $content->description = 'Look at the features that are essencial to a good and organized content'; $content->keywords = 'wiki features text image wysihtml5 multi idiom featured versioning'; $content->idiom = new Idiom($idiom_en->code); $content->featured = 1; $content->author = $account->username; $bean = R::dispense('content'); R::store($content->exportToBean($bean)); $content = new Content('How To Install', '<p>Dependencies: Apache + PHP5.3 + Sqlite (or LAMP), Composer and Git</p> <p>How to install:</p> <p>Download zip file from <a href="https://github.com/taviroquai/BootWiki">https://github.com/taviroquai/BootWiki</a> and extract to a folder as /var/www/html/bootwiki</p> <p>Open in browser <strong>http://localhost/bootwiki</strong> and follow installer instructions</p> <p>Login with admin user and admin password</p>'); $content->intro = '<p>Follow the few steps to install on linux</p>'; $content->description = 'Follow the few steps to install on linux'; $content->keywords = 'wiki install steps'; $content->idiom = new Idiom($idiom_en->code); $content->featured = 1; $content->author = $account->username; $bean = R::dispense('content'); R::store($content->exportToBean($bean)); $content = new Content('Documentation', '<p>Source code is at <a href="http://github.com/taviroquai/BootWiki">BootWiki on GitHub!</p>'); $content->intro = '<p>See the documentation, yet in development, for BootWiki usage</p>'; $content->description = 'See the documentation, yet in development, for BootWiki usage'; $content->keywords = 'wiki documentation'; $content->idiom = new Idiom($idiom_en->code); $content->featured = 1; $content->author = $account->username; $bean = R::dispense('content'); R::store($content->exportToBean($bean)); // Portuguese content $idiom_pt = R::dispense('idiom'); $idiom_pt->code = 'pt'; $idiom_pt->name = 'Português'; $idiom_pt->flag_image = 'web/img/flags/Portugal.png'; R::store($idiom_pt); $content = new Content('Bem-vindo à Wiki!', '<p>A Wiki built upon Twitter Bootstrap, RedBeanPHP and Slim Framework</p>'); $content->intro = '<p>Uma Wiki muito básica mas bonita para a sua organização</p>'; $content->description = 'Uma Wiki muito básica mas bonita para a sua organização'; $content->keywords = 'wiki bootstrap redbeanphp slim bonita simples organização'; $content->idiom = new Idiom($idiom_pt->code); $content->featured = 1; $content->author = $account->username; $bean = R::dispense('content'); R::store($content->exportToBean($bean)); $content = new Content('Funcionalidades', '<ul><li>Adição de conteúdo</li> <li>Listagem por mais recentes</li> <li>Listagem por mais vistos</li> <li>Pesquisa por palavras-chave</li> <li>Editor WYSIHTML5</li> <li>Upload de imagens</li> <li>Multi-idioma</li> <li>Configuração de destaques na homepage</li> <li>Sistema de revisões</li></ul>'); $content->intro = '<p>Veja as funcionalidades que são essenciais para uma uma boa apresentação de conteúdo</p>'; $content->description = 'Veja as funcionalidades que são essenciais para uma uma boa apresentação de conteúdo'; $content->keywords = 'wiki funcionalidades texto image wysihtml5 multi idioma destaques reviões'; $content->idiom = new Idiom($idiom_pt->code); $content->featured = 1; $content->author = $account->username; $bean = R::dispense('content'); R::store($content->exportToBean($bean)); $content = new Content('Como instalar', '<p>Dependências: Apache + PHP5.3 + Sqlite (or LAMP), Composer and Git</p> <p>Como instalar:</p> <p>Descarregue o ficheiro ZIP de <a href="https://github.com/taviroquai/BootWiki">https://github.com/taviroquai/BootWiki</a> e extraia para uma pasta do servidor web.</p> <p>No browser, abra o endereço http://localhost/bootwiki e siga as instruções</p>'); $content->intro = '<p>Siga os simples passos de instalação para linux</p>'; $content->description = 'Siga os simples passos de instalação para linux'; $content->keywords = 'wiki install'; $content->idiom = new Idiom($idiom_pt->code); $content->featured = 1; $content->author = $account->username; $bean = R::dispense('content'); R::store($content->exportToBean($bean)); $content = new Content('Documentação', '<p>Código fonte em <a href="http://github.com/taviroquai/BootWiki">BootWiki no GitHub!</p>'); $content->intro = '<p>Veja a documentação, ainda em desenvolvimento, para a utilização da BootWiki</p>'; $content->description = 'Veja a documentação, ainda em desenvolvimento, para a utilização da BootWiki'; $content->keywords = 'wiki documentação'; $content->idiom = new Idiom($idiom_pt->code); $content->featured = 1; $content->author = $account->username; $bean = R::dispense('content'); R::store($content->exportToBean($bean)); }
<?php use RedBean_Facade as R; $payload = $app->request()->getBody(); if (empty($payload['name'])) { throw new \Exception('name is required!', 412); } $user = R::dispense('user'); $user->name = $payload['name']; R::store($user); $app->result = $user->export();
/** * Processes a JSON object request. * * @param array $jsonObject JSON request object * * @return mixed $result result */ public function handleJSONRequest($jsonString) { //Decode JSON string $jsonArray = json_decode($jsonString, true); if (!$jsonArray) { return $this->resp(null, null, -32700, 'Cannot Parse JSON'); } if (!isset($jsonArray['jsonrpc'])) { return $this->resp(null, null, -32600, 'No RPC version'); } if ($jsonArray['jsonrpc'] != '2.0') { return $this->resp(null, null, -32600, 'Incompatible RPC Version'); } //DO we have an ID to identify this request? if (!isset($jsonArray['id'])) { return $this->resp(null, null, -32600, 'No ID'); } //Fetch the request Identification String. $id = $jsonArray['id']; //Do we have a method? if (!isset($jsonArray['method'])) { return $this->resp(null, $id, -32600, 'No method'); } //Do we have params? if (!isset($jsonArray['params'])) { $data = array(); } else { $data = $jsonArray['params']; } //Check method signature $method = explode(':', trim($jsonArray['method'])); if (count($method) != 2) { return $this->resp(null, $id, -32600, 'Invalid method signature. Use: BEAN:ACTION'); } //Collect Bean and Action $beanType = $method[0]; $action = $method[1]; //May not contain anything other than ALPHA NUMERIC chars and _ if (preg_match('/\\W/', $beanType)) { return $this->resp(null, $id, -32600, 'Invalid Bean Type String'); } if (preg_match('/\\W/', $action)) { return $this->resp(null, $id, -32600, 'Invalid Action String'); } try { switch ($action) { case 'store': if (!isset($data[0])) { return $this->resp(null, $id, -32602, 'First param needs to be Bean Object'); } $data = $data[0]; if (!isset($data['id'])) { $bean = RedBean_Facade::dispense($beanType); } else { $bean = RedBean_Facade::load($beanType, $data['id']); } $bean->import($data); $rid = RedBean_Facade::store($bean); return $this->resp($rid, $id); case 'load': if (!isset($data[0])) { return $this->resp(null, $id, -32602, 'First param needs to be Bean ID'); } $bean = RedBean_Facade::load($beanType, $data[0]); return $this->resp($bean->export(), $id); case 'trash': if (!isset($data[0])) { return $this->resp(null, $id, -32602, 'First param needs to be Bean ID'); } $bean = RedBean_Facade::load($beanType, $data[0]); RedBean_Facade::trash($bean); return $this->resp('OK', $id); default: $modelName = $this->modelHelper->getModelName($beanType); if (!class_exists($modelName)) { return $this->resp(null, $id, -32601, 'No such bean in the can!'); } $beanModel = new $modelName(); if (!method_exists($beanModel, $action)) { return $this->resp(null, $id, -32601, "Method not found in Bean: {$beanType} "); } return $this->resp(call_user_func_array(array($beanModel, $action), $data), $id); } } catch (Exception $exception) { return $this->resp(null, $id, -32099, $exception->getCode() . '-' . $exception->getMessage()); } }
/** * This method will inspect the array provided and load/dispense the * desired beans. To dispense a new bean, the array must contain: * * array( "newuser"=> array("type"=>"user","name"=>"John") ) * * - Creates a new bean of type user, property name is set to "John" * * To load a bean (for association): * * array( "theaddress"=> array("type"=>"address","id"=>2) ) * * - Loads a bean of type address with ID 2 * * Now to associate this bean in your form: * * array("associations"=>array( "0" => array( "newuser-theaddress" ) )) * * - Associates the beans under keys newuser and theaddress. * * To modify an existing bean: * * array("existinguser"=>array("type"=>"user","id"=>2,"name"=>"Peter")) * * - Changes name of bean of type user with ID 2 to 'Peter' * * This function returns: * * array( * "can" => an array with beans, either loaded or dispensed and populated * "pairs" => an array with pairs of beans to be associated * "sorted" => sorted by type * ); * * Note that this function actually does not store or associate anything at all, * it just prepares two arrays. * * @static * @param $post the POST array containing the form data * @return array hash table containing 'can' and 'pairs' * */ public static function load($post, RedBean_ToolBox $toolbox) { $writer = $toolbox->getWriter(); //fetch associations first and remove them from the array. if (isset($post["associations"])) { $associations = $post["associations"]; unset($post["associations"]); } //We store beans here $can = $pairs = $sorted = array(); foreach ($post as $key => $rawBean) { if (is_array($rawBean) && isset($rawBean["type"])) { //get type and remove it from array $type = $rawBean["type"]; unset($rawBean["type"]); //does it have an ID? $idfield = $writer->getIDField($type); if (isset($rawBean[$idfield])) { //yupz, get the id and remove it from array $id = $rawBean[$idfield]; //ID == 0, and no more fields then this is an NULL option for a relation, skip. if ($id == 0 && count($rawBean) === 1) { continue; } unset($rawBean[$idfield]); //now we have the id, load the bean and store it in the can $bean = RedBean_Facade::load($type, $id); } else { //no id? then get a new bean... $bean = RedBean_Facade::dispense($type); } //do we need to modify this bean? 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); //first check if we can find the key in the can, --only key 1 is able to load 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); }