public function show_Join() { // check if player is already playing some round $isPlaying = R::getCell("SELECT\n\t\t\tcount(pp.id)\n\t\tFROM\n\t\t\tpoker_player AS pp, poker_round AS pr,\n\t\t\tpoker_player_poker_round AS conn\n\t\tWHERE\n\t\t\t(pr.state = 'running' OR pr.state = 'pending') AND\n\t\t\tconn.poker_player_id = pp.id AND\n\t\t\tconn.poker_round_id = pr.id AND\n\t\t\tpp.id = ?", array($this->_pokerPlayer->getID())); if ($isPlaying > 0) { $this->output('state', 'join_ok'); return; } // count number of players in current&pending round $num = R::getCell("SELECT\n\t\t\tcount(pp.id)\n\t\tFROM\n\t\t\tpoker_player AS pp, poker_round AS pr,\n\t\t\tpoker_player_poker_round As conn\n\t\tWHERE\n\t\t\t(pr.state = 'running' OR pr.state = 'pending') AND\n\t\t\tconn.poker_player_id = pp.id AND\n\t\t\tconn.poker_round_id = pr.id"); if ($num >= 8) { $this->output('state', 'table_full'); } else { // get next pending round $pending = R::findOne('poker_round', " state = 'pending'"); if ($pending == null) { // open new pending round $pending = R::dispense('poker_round'); $pending->state = 'pending'; $pending->step = 0; $pending->cards = ''; $pending->ttl = time(); $pending->current_player = null; R::store($pending); } R::associate($this->_pokerPlayer, $pending); $this->output('state', 'join_ok'); } }
/** * add right to user * @param string $type * @return boolean */ public function addRight($type) { $right = RCached::findOne('user_right', ' type = ?', array($type), date("d.m.Y")); if (!$right) { return false; } R::associate($this->bean, $right); return true; }
public function giveNewQuest(RedBean_OODBBean $user) { $allQuests = Config::getConfig('npc_quests'); $rnd = array_rand($allQuests, 1); $this->accepted = 0; $this->quest_id = $rnd; $this->startnpc = R::findOne('map_npc', ' map != ? ORDER BY RAND() LIMIT 1', array('adminhouse')); $this->stopnpc = R::findOne('map_npc', ' map != ? AND map != ? AND id != ? ORDER BY RAND() LIMIT 1', array($this->startnpc->map, 'adminhouse', $this->startnpc->getID())); R::store($this->bean); R::associate($this->bean, $user); }
/** * Test FUSE and model formatting. * * @todo move tagging tests to tag tester. * * @return void */ public function testFUSE() { $toolbox = R::$toolbox; $adapter = $toolbox->getDatabaseAdapter(); $blog = R::dispense('blog'); $blog->title = 'testing'; $blog->blog = 'tesing'; R::store($blog); $blogpost = R::load("blog", 1); $post = R::dispense("post"); $post->message = "hello"; R::associate($blog, $post); $a = R::getAll("select * from blog "); RedBean_ModelHelper::setModelFormatter(new mymodelformatter()); $w = R::dispense("weirdo"); asrt($w->blah(), "yes!"); R::tag($post, "lousy,smart"); asrt(implode(',', R::tag($post)), "lousy,smart"); R::tag($post, "clever,smart"); $tagz = implode(',', R::tag($post)); asrt($tagz == "smart,clever" || $tagz == "clever,smart", TRUE); R::tag($blog, array("smart", "interesting")); asrt(implode(',', R::tag($blog)), "smart,interesting"); try { R::tag($blog, array("smart", "interesting", "lousy!")); pass(); } catch (RedBean_Exception $e) { fail(); } asrt(implode(',', R::tag($blog)), "smart,interesting,lousy!"); asrt(implode(",", R::tag($blog)), "smart,interesting,lousy!"); R::untag($blog, array("smart", "interesting")); asrt(implode(",", R::tag($blog)), "lousy!"); asrt(R::hasTag($blog, array("lousy!")), TRUE); asrt(R::hasTag($blog, array("lousy!", "smart")), TRUE); asrt(R::hasTag($blog, array("lousy!", "smart"), TRUE), FALSE); R::tag($blog, FALSE); asrt(count(R::tag($blog)), 0); R::tag($blog, array("funny", "comic")); asrt(count(R::tag($blog)), 2); R::addTags($blog, array("halloween")); asrt(count(R::tag($blog)), 3); asrt(R::hasTag($blog, array("funny", "commic", "halloween"), TRUE), FALSE); R::unTag($blog, array("funny")); R::addTags($blog, "horror"); asrt(count(R::tag($blog)), 3); asrt(R::hasTag($blog, array("horror", "commic", "halloween"), TRUE), FALSE); // No double tags R::addTags($blog, "horror"); asrt(R::hasTag($blog, array("horror", "commic", "halloween"), TRUE), FALSE); asrt(count(R::tag($blog)), 3); }
public function showdown() { $allPlayers = R::related($this->bean, 'poker_player'); $pokerHands = array(10 => new PokerParser("[a>a>a>a>a"), 9 => new PokerParser("a>a>a>a>a"), 8 => new PokerParser("1{4}"), 7 => new PokerParser("1{3}2{2}"), 6 => new PokerParser("a{5}"), 5 => new PokerParser("?>?>?>?>?"), 4 => new PokerParser("1{3}"), 3 => new PokerParser("1{2}2{2}"), 2 => new PokerParser("1{2}"), 1 => new PokerParser("?")); $bestValue = -1; $winners = array(); $totalPot = $this->bean->global_pot; // new round to move players to $nextRound = R::findOne('poker_round', " state='pending'"); if ($nextRound == null) { $nextRound = R::dispense('poker_round'); $nextRound->state = 'pending'; $nextRound->step = 0; $nextRound->global_pot = 0; R::store($nextRound); } foreach ($allPlayers as $p) { $cards = array_merge(json_decode($p->cards, true), json_decode($this->bean->cards, true)); $totalPot += $p->bid; $val = 0; foreach ($pokerHands as $value => $parser) { if ($parser->check($cards)) { // player has this $val = $value * 100 + $parser->getHighestCardValue(); break; } } if ($val > $bestValue) { $bestValue = $val; $winners = array($p); } elseif ($val == $bestValue) { $winners[] = $p; } // kick from current round R::unassociate($this->bean, $p); // put into next round R::associate($nextRound, $p); } $winnerCount = count($winners); $winAmount = floor($totalPot / $winnerCount); $winnerNames = array(); foreach ($winners as $win) { $usr = R::relatedOne($win, 'user'); $usr->cash += $winAmount; $winnerNames[] = $usr->username; R::store($usr); } R::trash($this->bean); return array("winners" => $winnerNames, "amount" => $winAmount, "bestValue" => $bestValue); }
public function api_postcommit() { $revision = $_POST["rev"]; $message = $_POST["msg"]; $post = R::dispense('homepage_posts'); $post->title = "Update R" . $revision; $post->content = "Ein Update auf R" . $revision . " wurde aufgespielt. \nÄnderungen: \n\n" . $message; $post->link = ""; $post->time = time(); R::store($post); $usr = R::load('user', 10); R::associate($post, $usr); echo "ok"; }
/** User adds himself to a mailing list */ public static function subscribe() { if (!$_REQUEST['list']) { return RedView::set('error', "Choose a list."); } $list = R::load('list', $_REQUEST['list']); if (!$list->id) { return RedView::set('error', "List doesn't exist."); } $scrip = Model_Subscription::createBean($_REQUEST); $scrip->main = self::getUser(); R::associate($list, $scrip); $_SESSION['user'] = $scrip->main->export(); return RedView::set('message', 'Success!'); }
public function show_Main() { $poker_player = R::relatedOne($this->user, 'poker_player'); if ($poker_player == null) { $poker_player = R::dispense('poker_player'); $poker_player->status = 'view'; $poker_player->cards = ''; $poker_player->bid = 0; $poker_player->all_in = false; $poker_player->all_in_amount = 0; R::store($poker_player); R::associate($poker_player, $this->user); } if ($poker_player->status == 'view') { Framework::TPL()->assign('can_join', true); } }
function domainToAccount($domainname, $account, $account_id) { $owner = R::findOne('owner', 'account_id=?', array($account_id)); if ($owner === false) { $owner = R::dispense("owner"); $owner->name = $account; $owner->account_id = $account_id; $id = R::store($owner); } $domain = R::findOne('domain', 'name=?', array($domainname)); #$domain = R::load( 'domain', $id ); R::associate($owner, $domain); $otherDomainsDefinedInVhost = R::find("domain", "vhost_group_key = ?", array($domain->vhost_group_key)); foreach ($otherDomainsDefinedInVhost as $otherDomain) { if ($otherDomain->type === 'name') { continue; } R::associate($owner, $otherDomain); } }
public function save($runValidation = true) { foreach ($this->deferredRelateBeans as $bean) { R::associate($this->bean, $bean); if (!RedBeanDatabase::isFrozen()) { $types = array($this->bean->getMeta("type"), $bean->getMeta("type")); sort($types); $tableName = implode("_", $types); foreach ($types as $type) { $columnName = "{$type}_id"; RedBeanColumnTypeOptimizer::optimize($tableName, $columnName, 'id'); } } } $this->deferredRelateBeans = array(); foreach ($this->deferredUnrelateBeans as $bean) { R::unassociate($this->bean, $bean); } $this->deferredUnrelateBeans = array(); return true; }
/** * Basic tests through Facade. * * @return void */ public function testBasicThroughFacade() { $toolbox = R::$toolbox; $adapter = $toolbox->getDatabaseAdapter(); $writer = $toolbox->getWriter(); $redbean = $toolbox->getRedBean(); $pdo = $adapter->getDatabase(); $a = new RedBean_AssociationManager($toolbox); asrt(R::$redbean instanceof RedBean_OODB, TRUE); asrt(R::$toolbox instanceof RedBean_Toolbox, TRUE); asrt(R::$adapter instanceof RedBean_Adapter, TRUE); asrt(R::$writer instanceof RedBean_QueryWriter, TRUE); $book = R::dispense("book"); asrt($book instanceof RedBean_OODBBean, TRUE); $book->title = "a nice book"; $id = R::store($book); asrt($id > 0, TRUE); $book = R::load("book", (int) $id); asrt($book->title, "a nice book"); $author = R::dispense("author"); $author->name = "me"; R::store($author); $book9 = R::dispense("book"); $author9 = R::dispense("author"); $author9->name = "mr Nine"; $a9 = R::store($author9); $book9->author_id = $a9; $bk9 = R::store($book9); $book9 = R::load("book", $bk9); $author = R::load("author", $book9->author_id); asrt($author->name, "mr Nine"); R::trash($author); R::trash($book9); pass(); $book2 = R::dispense("book"); $book2->title = "second"; R::store($book2); R::associate($book, $book2); asrt(count(R::related($book, "book")), 1); $book3 = R::dispense("book"); $book3->title = "third"; R::store($book3); R::associate($book, $book3); asrt(count(R::related($book, "book")), 2); asrt(count(R::find("book")), 3); asrt(count(R::findAll("book")), 3); asrt(count(R::findAll("book", " WHERE ROWNUM <= 2")), 2); asrt(count(R::find("book", " id=id ")), 3); asrt(count(R::find("book", " title LIKE ?", array("third"))), 1); asrt(count(R::find("book", " title LIKE ?", array("%d%"))), 2); // Now with new SQL Helper argument asrt(count(R::find("book", R::$f->begin()->addSQL('title LIKE ? ')->put('third'))), 1); asrt(count(R::find("book", R::$f->begin()->addSQL('title LIKE ? ')->put('%d%'))), 2); asrt(count(R::find("book", R::$f->begin()->addSQL('title')->like(' ? ')->addSQL(' ORDER BY id ')->desc()->put('%d%'))), 2); //Find without where clause asrt(count(R::findAll('book', ' order by id')), 3); R::unassociate($book, $book2); asrt(count(R::related($book, "book")), 1); R::trash($book3); R::trash($book2); asrt(count(R::related($book, "book")), 0); asrt(count(R::getAll("SELECT * FROM book ")), 1); asrt(count(R::getCol("SELECT title FROM book ")), 1); asrt((int) R::getCell("SELECT 123 FROM DUAL "), 123); $book = R::dispense("book"); $book->title = "not so original title"; $author = R::dispense("author"); $author->name = "Bobby"; R::store($book); $aid = R::store($author); R::associate($book, $author); $author = R::findOne("author", " name = ? ", array("Bobby")); $books = R::related($author, "book"); $book = reset($books); testpack("Test Swap function in R-facade"); $book = R::dispense("book"); $book->title = "firstbook"; $book->rating = 2; $id1 = R::store($book); $book = R::dispense("book"); $book->title = "secondbook"; $book->rating = 3; $id2 = R::store($book); $book1 = R::load("book", $id1); $book2 = R::load("book", $id2); asrt($book1->rating, '2'); asrt($book2->rating, '3'); $books = R::batch("book", array($id1, $id2)); R::swap($books, "rating"); $book1 = R::load("book", $id1); $book2 = R::load("book", $id2); asrt($book1->rating, '3'); asrt($book2->rating, '2'); testpack("Test R::convertToBeans"); $SQL = "SELECT '1' as id, a.name AS name, b.title AS title, '123' as rating FROM author a LEFT JOIN book b ON b.id = ? WHERE a.id = ? "; $rows = R::$adapter->get($SQL, array($id2, $aid)); $beans = R::convertToBeans("something", $rows); $bean = reset($beans); asrt($bean->getMeta("type"), "something"); asrt($bean->name, "Bobby"); asrt($bean->title, "secondbook"); asrt($bean->rating, "123"); testpack("Ext Assoc with facade and findRelated"); R::nuke(); $cd = R::dispense("cd"); $cd->title = "Midnight Jazzfest"; R::store($cd); $track = R::dispense("track"); $track->title = "Night in Tunesia"; $track2 = R::dispense("track"); $track2->title = "Stompin at one o clock"; $track3 = R::dispense("track"); $track3->title = "Nightlife"; R::store($track); R::store($track2); R::store($track3); // Assoc ext with json R::associate($track, $cd, '{"order":1}'); pass(); // Width array R::associate($track2, $cd, array("order" => 2)); pass(); R::associate($track3, $cd, '{"order":3}'); pass(); $tracks = R::related($cd, "track", " title LIKE ? ", array("Night%")); asrt(count($tracks), 2); $track = array_pop($tracks); asrt(strpos($track->title, "Night") === 0, TRUE); $track = array_pop($tracks); asrt(strpos($track->title, "Night") === 0, TRUE); $track = R::dispense("track"); $track->title = "test"; R::associate($track, $cd, "this column should be named extra"); asrt(R::getCell("SELECT count(*) FROM cd_track WHERE extra = 'this column should be named extra' "), "1"); $composer = R::dispense("performer"); $composer->name = "Miles Davis"; R::store($composer); }
public static function tag(RedBean_OODBBean $bean, $tagList = null) { if (is_null($tagList)) { $tags = R::related($bean, "tag"); $foundTags = array(); foreach ($tags as $tag) { $foundTags[] = $tag->title; } if (self::$flagUseLegacyTaggingAPI) { return implode(",", $foundTags); } return $foundTags; } if ($tagList !== false && !is_array($tagList)) { $tags = explode(",", (string) $tagList); } else { $tags = $tagList; } R::clearRelations($bean, "tag"); if ($tagList === false) { return; } foreach ($tags as $tag) { $t = R::findOne("tag", " title = ? ", array($tag)); if (!$t) { $t = R::dispense("tag"); $t->title = $tag; R::store($t); } R::associate($bean, $t); } }
public function exec($params) { $data = unserialize(base64_decode($_POST['data'])); $linker = mvc\retrieve('beanLinker'); if ($data['hostname'] == null || empty($data['hostname'])) { die('Missing hostname'); } $server = R::findOne("server", "name = ? ", array($data['hostname'])); if (!$server instanceof RedBean_OODBBean) { $server = R::dispense('server'); $server->created = mktime(); } $server->updated = mktime(); $server->name = $data['hostname']; $server->int_ip = $data['ipaddress']; $server->ext_ip = preg_match('/^(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:[.](?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}$/', $data['external_ip']) ? $data['external_ip'] : ''; $hardware = array('memory' => $data['memorysize'], 'cpucount' => $data['processorcount'], 'cpu' => $data['processor0']); if (isset($data['disk']['partitions'])) { $hardware['partitions'] = $data['disk']['partitions']; } $server->kernel_release = $data['kernelrelease']; $server->os = $data['lsbdistid']; $server->os_release = $data['lsbdistrelease']; $server->arch = $data['hardwaremodel']; $server->hardware = serialize($hardware); $server->type = $data['virtual']; $server->comment = $server->comment; // keep existing comment - should be dropped when schema is frozen $server->is_active = true; $server->uptime = isset($data['uptime']) ? $data['uptime'] : 0.0; $server->software_updates = !empty($data['software_updates']) ? serialize($data['software_updates']) : null; $serverID = R::store($server); if (isset($data['disk']['physical'])) { foreach ($data['disk']['physical'] as $disk) { // TODO: set drives inactive to make sure only active drives are is_active = true; $drive = R::findOne("drive", "serial_no=?", array($disk['SerialNo'])); if (!$drive instanceof RedBean_OODBBean) { $drive = R::dispense('drive'); $drive->created = mktime(); $drive->updated = mktime(); $drive->is_active = true; $drive->setBrand($disk['Model']); $drive->model = $disk['Model']; $drive->serial_no = $disk['SerialNo']; $drive->fw_revision = $disk['FwRev']; $drive->type = $disk['type']; } else { $drive->is_active = true; $drive->updated = mktime(); } R::store($drive); R::associate($server, $drive); } } if ($server->type === 'xen0' && isset($data['domUs']) && !empty($data['domUs'])) { foreach ($data['domUs'] as $domUName) { $domU = array(); $result = array(); $domU = R::findOne("server", "name=?", array($domUName)); if (!$domU instanceof RedBean_OODBBean) { $domU = R::dispense('server'); $domU->name = $domUName; $domU->created = mktime(); $domU->updated = mktime(); $domU->type = 'xenu'; R::attach($server, $domU); $domUID = R::store($domU); } else { $domU->updated = mktime(); R::attach($server, $domU); // server is parent of domU } } } // Handle domains if (isset($data['vhosts'])) { $updateTimestamp = mktime(); foreach ($data['vhosts'] as $v) { $vhost = R::findOne('vhost', 'server_id=? AND server_name=?', array($serverID, $v['servername'])); if (!$vhost instanceof RedBean_OODBBean) { $vhost = R::dispense('vhost'); $vhost->created = $updateTimestamp; } $vhost->updated = $updateTimestamp; $vhost->server_name = $v['servername']; $vhost->file_name = isset($v['filename']) ? $v['filename'] : null; $vhost->document_root = isset($v['documentroot']) ? $v['documentroot'] : null; $vhost->server_admin = isset($v['serveradmin']) ? $v['serveradmin'] : null; $app = null; if (isset($v['app']['name'])) { $app = R::findOne('app', 'name=?', array($v['app']['name'])); if (!$app instanceof RedBean_OODBBean) { $app = R::dispense('app'); $app->name = $v['app']['name']; R::store($app); } } $vhost->app_version = isset($v['app']['version']) ? $v['app']['version'] : null; //$vhost->is_valid = true; $vhost->comment = ''; if ($app instanceof RedBean_OODBBean) { $linker->link($vhost, $app); } $linker->link($vhost, $server); $vhostID = R::store($vhost); foreach ($v['domains'] as $domainEntry) { if (empty($domainEntry['name'])) { continue; } $domainParts = array(); $domainParts = array_reverse(explode('.', $domainEntry['name'])); // TODO: check if 2 first parts are an ccTLD, see http://publicsuffix.org/list/ $tld = null; $sld = null; $sub = null; $tld = array_shift($domainParts); $sld = array_shift($domainParts); $sub = !empty($domainParts) ? implode('.', array_reverse($domainParts)) : null; /* $sql = 'sub=? AND sld=? AND tld=? AND vhost_id=?'; $args = array($sub,$sld,$tld,$vhostID); if ( is_null($sub) ) { $sql = 'sub IS NULL AND sld=? AND tld=? AND vhost_id=?'; $args = array($sld,$tld,$vhostID); } $domain = R::findOne('domain',$sql,$args); */ $domain = R::findOne('domain', 'name = ?', array($domainEntry['name'])); if (!$domain instanceof RedBean_OODBBean) { $domain = R::dispense('domain'); $domain->created = $updateTimestamp; } $domain->updated = $updateTimestamp; $domain->sub = empty($sub) ? null : $sub; $domain->sld = $sld; $domain->tld = $tld; $domain->name = $domainEntry['name']; $domain->is_active = true; //$linker->link($domain,$vhost); $domainID = R::store($domain); $vhostEntry = R::findOne('vhostEntry', 'type = ? AND vhost_id = ? AND domain_id = ?', array($domainEntry['type'], $vhostID, $domainID)); if (!$vhostEntry instanceof RedBean_OODBBean) { $vhostEntry = R::dispense('vhostEntry'); $vhostEntry->created = $updateTimestamp; $vhostEntry->is_valid = true; $vhostEntry->note = ''; } $vhostEntry->type = $domainEntry['type']; $vhostEntry->updated = $updateTimestamp; $linker->link($vhostEntry, $vhost); $linker->link($vhostEntry, $domain); $linker->link($vhostEntry, $server); R::store($vhostEntry); } // set is_active to false for those domains in the current vhost which has not been updated /*$notUpdatedDomains = R::find("domain","updated != ? AND vhost_id = ?", array( $updateTimestamp, $vhostID )); $domain = array(); foreach ($notUpdatedDomains as $domain) { $domain->is_active = false; $domainID = R::store($domain); }*/ } } }
function testViews($p) { R::exec(" drop table if exists bandmember_musician CASCADE"); R::exec(" drop table if exists band_bandmember CASCADE"); R::exec(" drop table if exists prefix_bandmember_musician CASCADE"); R::exec(" drop table if exists prefix_band_bandmember CASCADE"); R::exec(" drop table if exists musician CASCADE "); R::exec(" drop table if exists bandmember CASCADE"); R::exec(" drop table if exists band CASCADE"); R::exec(" drop table if exists prefix_musician CASCADE"); R::exec(" drop table if exists prefix_bandmember CASCADE"); R::exec(" drop table if exists prefix_band CASCADE"); list($mickey, $donald, $goofy) = R::dispense("musician", 3); list($vocals1, $vocals2, $keyboard1, $drums, $vocals3, $keyboard2) = R::dispense("bandmember", 6); list($band1, $band2) = R::dispense("band", 2); $band1->name = "The Groofy"; $band2->name = "Wickey Mickey"; $mickey->name = "Mickey"; $goofy->name = "Goofy"; $donald->name = "Donald"; $vocals1->instrument = "voice"; $vocals2->instrument = "voice"; $keyboard1->instrument = "keyboard"; $drums->instrument = "drums"; $vocals3->instrument = "voice"; $keyboard2->instrument = "keyboard"; $vocals3->bandleader = true; $drums->bandleader = true; $drums->notes = "noisy"; $vocals3->notes = "tenor"; R::associate($mickey, $vocals1); R::associate($donald, $vocals2); R::associate($donald, $keyboard1); R::associate($goofy, $drums); R::associate($mickey, $vocals3); R::associate($donald, $keyboard2); R::associate($band1, $vocals1); R::associate($band1, $vocals2); R::associate($band1, $keyboard1); R::associate($band1, $drums); R::associate($band2, $vocals3); R::associate($band2, $keyboard2); try { R::view("bandlist", "band"); fail(); } catch (Exception $e) { pass(); } try { R::view("bandlist", "band,bandmember,musician"); pass(); } catch (Exception $e) { print_r($e); fail(); } //can we do a simple query? $nameOfBandWithID1 = R::getCell("select name from " . $p . "bandlist where " . R::$writer->getIDField("band") . " = 1\ngroup by " . R::$writer->getIDField("band") . ",\"name\""); asrt($nameOfBandWithID1, "The Groofy"); //can we generate a report? list all bandleaders $bandleaders = R::getAll("select bandleader_of_bandmember,name_of_musician,\"name\" AS bandname\n\tfrom " . $p . "bandlist where bandleader_of_bandmember = 1 group by id "); foreach ($bandleaders as $bl) { if ($bl["bandname"] == "Wickey Mickey") { asrt($bl["name_of_musician"], "Mickey"); } if ($bl["bandname"] == "The Groofy") { asrt($bl["name_of_musician"], "Goofy"); } } //can we draw statistics? $inHowManyBandsDoYouPlay = R::getAll("select\nname_of_musician ,count( distinct " . R::$writer->getIDField("band") . ") as bands\nfrom " . $p . "bandlist group by " . R::$writer->getIDField("musician") . "_of_musician,name_of_musician order by name_of_musician asc\n"); asrt($inHowManyBandsDoYouPlay[0]["name_of_musician"], "Donald"); asrt($inHowManyBandsDoYouPlay[0]["bands"], '2'); asrt($inHowManyBandsDoYouPlay[1]["name_of_musician"], "Goofy"); asrt($inHowManyBandsDoYouPlay[1]["bands"], '1'); asrt($inHowManyBandsDoYouPlay[2]["name_of_musician"], "Mickey"); asrt($inHowManyBandsDoYouPlay[2]["bands"], '2'); //who plays in band 2 //can we make a selectbox $selectbox = R::getAll("\n\tselect m." . R::$writer->getIDField("musician") . ", m.name, b." . R::$writer->getIDField("band") . " as selected from " . $p . "musician as m\n\tleft join " . $p . "bandlist as b on b." . R::$writer->getIDField("musician") . "_of_musician = m." . R::$writer->getIDField("musician") . " and\n\tb." . R::$writer->getIDField("band") . " =2\n\torder by m.name asc\n"); asrt($selectbox[0]["name"], "Donald"); asrt($selectbox[0]["selected"], "2"); asrt($selectbox[1]["name"], "Goofy"); asrt($selectbox[1]["selected"], null); asrt($selectbox[2]["name"], "Mickey"); asrt($selectbox[2]["selected"], "2"); }
/** * Test creation of link table. * * @return void */ public function testCreationOfLinkTable() { asrt(in_array('consult', R::$writer->getTables()), FALSE); $d = R::dispense('doctor')->setAttr('name', 'd1'); $p = R::dispense('patient')->setAttr('name', 'p1'); R::associate($d, $p); asrt(in_array('consult', R::$writer->getTables()), TRUE); }
/** * Test usage of named parameters in SQL snippets. * Issue #299 on Github. * * @return void */ public function testNamedParamsInSnippets() { testpack('Test whether we can use named parameters in SQL snippets.'); R::nuke(); $book = R::dispense('book'); $page = R::dispense('page'); $book->title = 'book'; R::associate($book, $page); //should not give error like: Uncaught [HY093] - SQLSTATE[HY093]: Invalid parameter number: mixed named and positional parameters $books = R::related($page, 'book', ' title = :title ', array(':title' => 'book')); asrt(count($books), 1); //should not give error... $books = $page->withCondition(' title = :title ', array(':title' => 'book'))->sharedBook; asrt(count($books), 1); //should not give error... $links = R::$associationManager->related($page, 'book', TRUE, ' title = :title ', array(':title' => 'book')); asrt(count($links), 1); $book2 = R::dispense('book'); R::associate($book, $book2); //cross table, duplicate slots? $books = R::related($book2, 'book', ' title = :title ', array(':title' => 'book')); asrt(count($books), 1); R::nuke(); $book = R::dispense('book'); $page = R::dispense('page'); $book->title = 'book'; $book->comment = 'comment'; $page->title = 'page'; $book->ownPage[] = $page; R::store($book); //should also not give error.. $count = $book->countOwn('page'); asrt($count, 1); $book = $book->fresh(); //should also not give error.. $count = $book->withCondition(' title = ? ', array('page'))->countOwn('page'); asrt($count, 1); $book = $book->fresh(); //should also not give error.. $count = $book->withCondition(' title = :title ', array(':title' => 'page'))->countOwn('page'); asrt($count, 1); $book = $book->fresh(); $pages = $book->withCondition(' title = :title ', array(':title' => 'page'))->ownPage; asrt(count($pages), 1); //test with duplicate slots... $page = reset($pages); $page2 = R::dispense('page'); $page2->ownPage[] = $page; R::store($page2); $page2 = $page2->fresh(); $pages = $page2->withCondition(' title = :title ', array(':title' => 'page'))->ownPage; asrt(count($pages), 1); //test with find() $books = R::$redbean->find('book', array('title' => array('book')), ' AND title = :title ', array(':title' => 'book')); asrt(count($books), 1); $books = R::$redbean->find('book', array('title' => array('book', 'book2'), 'comment' => array('comment', 'comment2')), ' AND title = :title ', array(':title' => 'book')); asrt(count($books), 1); //just check numeric works as well... $books = R::$redbean->find('book', array('title' => array('book', 'book2'), 'comment' => array('comment', 'comment2')), ' AND title = ? ', array('book')); asrt(count($books), 1); //just extra check to verify glue works $books = R::$redbean->find('book', array('title' => array('book', 'book2'), 'comment' => array('comment', 'comment2')), ' ORDER BY id '); asrt(count($books), 1); //also check with preloader $book = $book->fresh(); R::preload($book, array('ownPage' => array('page', array(' title = :title ', array(':title' => 'page'))))); asrt(count($book->ownPage), 1); }
private function posthookHomepage_posts(&$bean) { if (!R::areRelated($bean, $this->user)) { R::associate($bean, $this->user); } }
/** * handle company rules */ protected function cronHandleCrule() { // delete old rules R::exec('DELETE FROM `crule` WHERE `until` < ?', array(time())); // get new rules $crules = R::find('crule'); // counter $counter = array('buy' => 0, 'sell' => 0); foreach ($crules as $crule) { $company = R::relatedOne($crule, 'company'); $amount = R::getCell('SELECT `' . $crule->r_name . '` FROM `company_' . ($crule->r_type == 'product' ? 'products' : 'ress') . '` WHERE company_id = ?', array($company->id)); // fix amount with existant orders $existant = R::related($company, 'order', 'r_name = ? AND type = ?', array($crule->r_name, $crule->action)); foreach ($existant as $e) { if ($e->type == 'buy') { $amount += $e->r_amount; } else { $amount -= $e->r_amount; } } $order = R::dispense('order'); $order->type = $crule->action; $order->r_type = $crule->r_type; $order->r_name = $crule->r_name; $order->price = $crule->r_price; $order->date = time(); $order->automatic = false; $order->a_expires = 0; $sold = 0; if ($crule->action == 'buy' && $amount < $crule->r_limit) { // create buy order $maxBuy = $crule->r_limit - $amount; $costs = $maxBuy * $crule->r_price; if ($costs > $company->balance) { $maxBuy = floor($company->balance / $crule->r_price); } if ($maxBuy == 0) { continue; } $company->balance -= $maxBuy * $crule->r_price; $order->r_amount = $maxBuy; $counter['buy']++; } else { if ($crule->action == 'sell' && $amount > $crule->r_limit) { // create sell order $order->r_amount = $amount - $crule->r_limit; $sold += $amount - $crule->r_limit; $counter['sell']++; } else { continue; } } R::begin(); if ($sold != 0) { R::exec('UPDATE `company_' . ($crule->r_type == 'product' ? 'products' : 'ress') . '` SET `' . $crule->r_name . '` = `' . $crule->r_name . '`-? WHERE company_id = ?', array($sold, $company->id)); } R::store($order); R::store($company); R::associate($order, $company); R::commit(); } $this->log('handleCrule', $counter['buy'] . ' new buy-orders, ' . $counter['sell'] . ' new sell-orders'); }
/** * Tags a bean or returns tags associated with a bean. * If $tagList is null or omitted this method will return a * comma separated list of tags associated with the bean provided. * 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 string $commaSepListTags */ public static function tag( RedBean_OODBBean $bean, $tagList = null ) { if (is_null($tagList)) { $tags = R::related( $bean, "tag"); $foundTags = array(); foreach($tags as $tag) { $foundTags[] = $tag->title; } return implode(",",$foundTags); } if ($tagList!==false && !is_array($tagList)) $tags = explode( ",", (string)$tagList); else $tags=$tagList; if (is_array($tags)) { foreach($tags as $tag) { if (preg_match("/\W/",$tag)) throw new RedBean_Exception("Invalid Tag. Tags may only contain alpha-numeric characters"); } } R::clearRelations( $bean, "tag" ); if ($tagList===false) return; foreach($tags as $tag) { $t = R::findOne("tag"," title = ? ",array($tag)); if (!$t) { $t = R::dispense("tag"); $t->title = $tag; R::store($t); } R::associate( $bean, $t ); } }
/** * */ function cmp_ip($serverIP, RedBean_OODBBean $domain) { if (strpos($domain->name, '*') !== false) { throw new Exception('Domain name contains *'); } if ($dnsRecords = dns_get_record($domain->name)) { $error = true; $registeredIPs = array(); $related = R::related($domain, 'ip_address'); if (!empty($related)) { foreach ($related as $rel) { $registeredIPs[$rel->value] = $rel; } } $updateTimestamp = mktime(); foreach ($dnsRecords as $record) { if (!isset($record['type']) || !in_array($record['type'], array('A', 'NS'))) { continue; } switch ($record['type']) { case 'A': $value = $record['ip']; break; case 'NS': $value = $record['target']; break; } $ipAddress = null; if (empty($registeredIPs) || !isset($registeredIPs[$value])) { $ipAddress = R::dispense('ip_address'); $ipAddress->created = $updateTimestamp; $ipAddress->value = $value; $ipAddress->type = $record['type']; } else { if (isset($registeredIPs[$value])) { $ipAddress = $registeredIPs[$value]; unset($registeredIPs[$value]); } } if ($ipAddress instanceof RedBean_OODBBean) { $ipAddress->updated = $updateTimestamp; R::store($ipAddress); R::associate($domain, $ipAddress); } if ($record['type'] == 'A' && $record['ip'] == $serverIP) { $error = false; } } if (!empty($registeredIPs)) { foreach ($registeredIPs as $ip) { R::unassociate($ip, $domain); R::trash($ip); } } if ($error) { throw new Exception('Domain does not point to server'); } } else { throw new Exception('No A record exists, or domains does not exist'); } }
/** * Don't try to add foreign key constraints to * link table if they are already there. * * Actually this is pretty much dead code as this would normally never occur, * but we want 100% test coverage so we test this line anyway. */ public function testCheckConstraintAlreadyExists() { R::nuke(); $book = R::dispense('book'); $page = R::dispense('page'); R::associate($book, $page); $didAdd = R::$writer->addConstraintForTypes('book', 'page'); pass(); //can't really test this - just don't crash! }
public function show_Show_quests() { $quests = Config::getConfig('company_quests'); if ($this->get(1) == 'check') { $name = $this->get(2); if (!isset($quests[$name]) || $quests[$name]["level"] > $this->user->level) { $this->output('maintext', 'Du hast eine ungültige Aufgabe gewählt'); $this->output('options', array('show_quests' => 'Zurück')); return; } $quest = $quests[$name]; if ($this->get(3) == 'accept' && $this->get(4) == $_SESSION['secHash']) { unset($_SESSION['secHash']); // security $company_quest = R::dispense('company_quest'); $company_quest->name = $name; $company_quest->valid_until = time() + $quest["time"] * 24 * 3600; $company_quest->completed = false; R::store($company_quest); R::associate($this->user, $company_quest); $this->output('maintext', 'Du hast diese Aufgabe akzeptiert! Viel erfolg dabei!'); $this->output('options', array('show_quests' => 'Zurück')); return; } $th = ""; $td = ""; foreach ($quest["needs"] as $n) { $th .= "<th>{" . ($n["type"] == "resource" ? 'r' : 'p') . "_" . $n["name"] . "}</th>"; $td .= "<td>" . formatCash($n["amount"]) . "</td>"; } $this->output('maintext', '<h3>' . htmlspecialchars($quest["title"]) . '</h3> <p>' . htmlspecialchars($quest["text"]) . '</p> <p>Du musst folgende Resourcen und Produkte abliefern:</p> <table class="ordered"> <tr> <th></th>' . $th . ' </tr> <tr> <td>Menge</td>' . $td . ' </tr> </table> <i>Du hast <b>' . $quest["time"] . ' Tage</b> Zeit um diesen Auftrag zu erledigen. Solltest du den Auftrag nicht in dieser Zeit erledigen wird der Auftrag abgebrochen. Außerdem musst du ' . formatCash(floor($quest["oncomplete"]["cash"] * 0.1)) . ' {money} Strafe zahlen, was automatisch von deinem Firmenkonto abgebucht wird. Du kannst den Auftrag danach erneut annehmen.</i> <p>Wenn du den Auftrag erledigst, bekommst du:</p> <table class="ordered"> <tr> <th>Erfahrungspunkte:</th> <td>' . formatCash($quest["oncomplete"]["xp"]) . ' {eye}</td> </tr> <tr> <th>Geld*:</th> <td>' . formatCash($quest["oncomplete"]["cash"]) . ' {money}</td> </tr> </table> <br /> <i>* das verdiente Geld wird auf das Firmenkonto überwiesen</i>'); $_SESSION['secHash'] = md5(time() . mt_rand(1000, 10000)); $this->output('options', array('show_quests/check/' . $name . '/accept/' . $_SESSION['secHash'] => 'Aufgabe annehmen', 'show_quests' => 'Zurück zur Übersicht')); return; } $this->output('maintext', 'Je nach deinem Level kannst du unterschiedliche Aufträge übernehmen. Sollten ich derzeit keine Aufträge mehr für dein Level haben, so sammel etwas Erfahrung und komm dann nochmal wieder! <br /> Folgende Aufträge kannst du zur Zeit für mich übernehmen:'); $oDesc = array(); $oOpt = array(); $todo = false; foreach ($quests as $name => $quest) { if ($quest["level"] > $this->user->level) { continue; } if (count($this->myQuests) > 0) { $isDone = false; foreach ($this->myQuests as $q) { if ($q->name == $name) { $isDone = true; break; } } if ($isDone) { continue; } } $todo = true; $oDesc["show_quests/check/" . $name] = "<hr /><h3>" . htmlspecialchars($quest["title"]) . "</h3>\n\t\t\t<p>" . htmlspecialchars($quest["text"]) . "</p>"; $oOpt["show_quests/check/" . $name] = "mehr Informationen"; } if (!$todo) { $oDesc["interact"] = "<i>Ich habe derzeit leider keine Aufträge für dich!</i>"; } else { $oDesc["interact"] = "<hr />"; } $oOpt["interact"] = "Zurück"; $this->output('options_desc', $oDesc); $this->output('options', $oOpt); }
public function exec($params) { register_shutdown_function(array($this, 'outPutJson')); $this->setJsonMsg(array('msg' => 'No data returned'), self::ERROR); switch ($params['action']) { case 'accountsToDomains': if (empty($_GET['account_id']) || empty($_GET['domains'])) { $this->setJsonMsg(array('msg' => 'Some fields are missing'), self::ERROR); } else { $owner = false; $owner = R::findOne('owner', 'account_id=?', array($_GET['account_id'])); if (!$owner instanceof RedBean_OODBBean) { $owner = R::dispense("owner"); $owner->name = $_GET['account_name']; $owner->account_id = $_GET['account_id']; $id = R::store($owner); } foreach ($_GET['domains'] as $id) { $domain = R::load('domain', $id); R::associate($owner, $domain); /*$otherDomainsDefinedInVhost = R::find("domain","vhost_id = ?",array($domain->vhost_id)); foreach ($otherDomainsDefinedInVhost as $otherDomain) { if ( in_array( $otherDomain->id, $_GET['domains'] ) ) { continue; } R::associate( $owner, $otherDomain ); }*/ } $domains = getUnrelatedMainDomains(); $html = ''; foreach ($domains as $domain) { $html .= '<option value="' . $domain->id . '">' . $domain->name . '</option>'; } $this->setJsonMsg(array('msg' => $owner->name . ' set as owner of domains', 'content' => $html)); } break; case 'getDomains': // TODO: use search $serverID = (int) $_GET['serverID']; $server = R::load("server", $serverID); $linker = mvc\retrieve('beanLinker'); $vhostEntries = R::find('vhostEntry', 'server_id = ?', array($server->id)); if (!empty($vhostEntries)) { $html = '<h1>Domains in vhosts on server (excluding www aliases)</h1><div class="domains list">'; foreach ($vhostEntries as $entry) { $domain = R::load('domain', $entry->domain_id); // ignore www aliases if ($domain->sub == 'www' && $domain->type == 'alias') { continue; } $html .= '<div class="domain"> <div class="status">' . (!$entry->is_valid ? '<img src="/design/desktop/images/error.png" title="' . $entry->note . '" class="icon"/>' : '') . '</div> <div class="name' . ($domain->is_active ? '' : ' inactive') . '">' . ($entry->type == 'alias' ? '- ' : '') . '<a href="http://' . $domain->getFQDN() . '">' . $domain->name . '</a></div> <br class="cls"> </div>'; } $html .= '</div>'; $this->setJsonMsg(array('msg' => 'ok', 'content' => $html)); } else { $this->setJsonMsg(array('msg' => 'No domains found on server'), self::WARNING); } break; case 'search': if (isset($_GET['query']) && isset($_GET['type'])) { $type = $_GET['type']; $query = $_GET['query']; $query = $query . '%'; if (isset($_GET['wildcards']) && $_GET['wildcards'] == 'both') { $query = '%' . $query; } $handler = new searchHandler($type); $json = $handler->query($query); $this->setJsonData($json); } else { $this->setJsonMsg(array('msg' => 'Missing paramaters'), self::ERROR); } break; case 'missingDomRelation': $servers = R::find("server", "type = ?", array('xenu')); $content = array(); foreach ($servers as $server) { $dom0 = false; $dom0 = R::getParent($server); if (!$dom0 instanceof RedBean_OODBBean || empty($dom0->name)) { $content[] = $server->name; } } if (empty($content)) { $this->setJsonMsg(array('msg' => 'No servers found', 'msg_type' => self::OK), self::ERROR); } else { $this->setJsonMsg(array('msg' => 'ok', 'content' => implode('<br>', $content))); } break; case 'missingFieldsOnServer': $servers = R::find("server"); $content = array(); $allowedMissing = array('comment'); foreach ($servers as $server) { $missingFields = array(); foreach ($server->getIterator() as $key => $value) { if (in_array($key, $allowedMissing)) { continue; } if (empty($value) || is_null($value)) { $missingFields[] = $key; } } if (!empty($missingFields)) { $content[] = 'Id: ' . $server->id . (!empty($server->name) ? ' (' . $server->name . ')' : '') . ' is missing: ' . implode(', ', $missingFields); } } $this->setJsonMsg(array('msg' => 'ok', 'content' => implode('<br>', $content))); break; case 'inactiveDomains': $domains = R::find("domain", "is_active=?", array(false)); $content = array(); foreach ($domains as $domain) { $server = R::load("server", $domain->server_id); $content[] = $domain->name . ' on ' . $server->name . ' last updated ' . date('d-m-Y H:i:s', $domain->updated); } if (empty($content)) { $this->setJsonMsg(array('msg' => 'No inactive domains found', 'msg_type' => self::OK), self::ERROR); } else { $this->setJsonMsg(array('msg' => 'ok', 'content' => implode('<br>', $content))); } break; case 'notUpdatedRecently': $content = array(); $type = $params['segments'][0][0]; $ts = mktime(); switch ($type) { case 'domains': $results = R::find("domain", "updated < ?", array($ts)); foreach ($results as $domain) { $content[] = $domain->getFQDN(); } break; case 'servers': $results = R::find("server", "updated < ?", array($ts)); foreach ($results as $result) { $content[] = $result->name; } break; } if (empty($content)) { $this->setJsonMsg(array('msg' => 'No ' . $type . ' not updated the last 3 days', 'msg_type' => self::OK), self::ERROR); } else { $this->setJsonMsg(array('msg' => 'ok', 'content' => implode('<br>', $content))); } break; case 'domainsWithForeignDNS': $dnsServers = mvc\retrieve('config')->dnsServers; if (is_array($dnsServers)) { $content = array(); $ipAddresses = R::find('ip_address', " type = 'NS' AND value NOT IN ('" . implode("', '", $dnsServers) . "') "); foreach ($ipAddresses as $ip) { $domains = R::related($ip, 'domain'); foreach ($domains as $domain) { $content[$domain->name] = $domain->name . ' (' . $ip->value . ')'; } } $this->setJsonMsg(array('msg' => 'ok', 'content' => implode('<br>', $content))); } else { $this->setJsonMsg(array('msg' => 'Please set "dnsServers" as an array in the config file'), self::ERROR); } break; // TODO: should be generalized to allow editing of other fields // TODO: should be generalized to allow editing of other fields case 'editServerComment': $serverID = (int) $_GET['serverID']; $server = R::load("server", $serverID); if ($server instanceof RedBean_OODBBean) { $content = '<form action="/service/ajax/saveServerComment/?serverID=' . $serverID . '" method="post" id="serverCommentForm"> <p> <textarea name="comment" rows="10" cols="50">' . $server->comment . '</textarea><br> <input type="submit" name="serverCommentSaveAction" value="Save" /> </p> </form'; $this->setJsonMsg(array('msg' => 'ok', 'content' => $content)); } else { $this->setJsonMsg(array('msg' => 'Unknown server'), self::ERROR); } break; // TODO: should be generalized to allow editing of other fields // TODO: should be generalized to allow editing of other fields case 'saveServerComment': $comment = $_GET['comment']; $serverID = (int) $_GET['serverID']; $server = R::load("server", $serverID); $server->comment = $comment; R::store($server); $this->setJsonMsg(array('msg' => 'Comment stored')); break; case 'setEnabledFields': $type = $_GET['type']; $availableFields = getAvaliableFields($type); $enabledFields = array(); foreach ($_GET['field'] as $key) { if (isset($availableFields[$key])) { $enabledFields[$key] = $availableFields[$key]; } } setcookie('enabledFields', serialize(array($type => $enabledFields)), time() + 36000, '/'); $this->setJsonMsg(array('msg' => 'Enabled fields set')); break; case 'getServerList': $data['hasFieldSelector'] = true; $data['avaliableFields'] = getAvaliableFields('servers'); $data['enabledFields'] = getEnabledFields('servers'); $data['serversGrouped'] = getGroupedByType(); $data['template'] = 'design/desktop/templates/servers_list.tpl.php'; ob_start(); mvc\render($data['template'], $data); $content = ob_get_clean(); $this->setJsonMsg(array('msg' => 'ok', 'content' => $content)); break; case 'getFieldList': // TODO: should not be hardcoded $avaliableFields = getAvaliableFields('servers'); $enabledFields = getEnabledFields('servers'); $avaliableLi = ''; $enabledLi = ''; $enabledFieldKeys = array_keys($enabledFields); foreach ($avaliableFields as $key => $prettyName) { if (in_array($key, $enabledFieldKeys)) { $enabledLi .= '<li id="field=' . $key . '">' . $prettyName . '</li>'; } else { $avaliableLi .= '<li id="field=' . $key . '">' . $prettyName . '</li>'; } } $content = '<div class="sortableListContainer first"> <h2>Enabled fields</h2> <ul class="connectedSortable" id="enabledFields"> ' . $enabledLi . ' </ul> </div> <div class="sortableListContainer last"> <h2>Avaliable fields</h2> <ul class="connectedSortable" id="avaliableFields"> ' . $avaliableLi . ' </ul> </div>'; $this->setJsonMsg(array('msg' => 'ok', 'content' => $content)); break; default: $this->setJsonMsg(array('msg' => 'Unknown action'), self::ERROR); break; } }
protected function actionCreate($action, $name, $details, $type, $id) { if (!isset($_POST['amount']) || !isset($_POST['price']) || !is_numeric($_POST['amount']) || !is_numeric($_POST['price']) || $_POST['amount'] <= 0 || $_POST['price'] <= 0) { $this->output('maintext', 'Ungültige Menge oder ungültier Preis!'); return; } $amount = $_POST['amount']; $price = $_POST['price']; if ($action == "sell" && $amount > ($type == 'r' ? $this->myRess->{$name} : $this->myProducts->{$name})) { $this->output('maintext', 'Du hast nicht genügend {' . $type . '_' . $name . '} für eine Verkaufsorder.'); return; } if ($action == "buy" && $price * $amount > $this->myCompany->balance) { $this->output('maintext', 'Du hast nicht genügend {money} auf dem Firmenkonto für eine Kaufsorder.'); return; } $order = R::dispense('order'); $order->type = $action; $order->r_type = $type == 'r' ? 'resource' : 'product'; $order->r_name = $name; $order->r_amount = $amount; $order->price = $price; $order->date = time(); if ($this->user->hasPremium()) { $order->automatic = isset($_POST['automatic']); if (!preg_match('#([0-9]{1,2})\\.([0-9]{1,2})\\.([0-9]{4})#i', $_POST['a_expires'], $m)) { $this->output('maintext', 'Das angegebene Ablaufdatum ist ungültig!.'); return; } $exp = mktime(date("H"), date("i"), date("s"), $m[2], $m[1], $m[3]); if ($exp < time() || $exp - time() > 60 * 24 * 3600) { $this->output('maintext', 'Das angegebene Ablaufdatum ist nicht in einem Zeitraum von 60 Tagen!'); return; } $order->a_expires = $exp; } else { $order->automatic = false; $order->a_expires = 0; } R::begin(); if ($action == "buy") { $this->myCompany->balance -= $price * $amount; R::store($this->myCompany); } elseif ($action == "sell") { if ($type == 'r') { $this->myRess->{$name} -= $amount; R::store($this->myRess); } else { $this->myProducts->{$name} -= $amount; R::store($this->myProducts); } } R::store($order); R::associate($this->myCompany, $order); R::commit(); $this->output('maintext', 'Die Order wurde erstellt!'); }
public function show_Add() { if (!$this->user->hasPremium()) { $this->error('Nur für Premiumaccounts.'); } if (isset($_POST['action'])) { $crule = R::dispense('crule'); if (!in_array($_POST['action'], array('buy', 'sell'))) { $this->output('maintext', 'Ungültige Aktion.'); $this->output('options', array('add' => 'Zurück')); return; } $crule->action = $_POST['action']; $ress = Config::getConfig('resources'); $prods = Config::getConfig('products'); if (!in_array($_POST['r_name'], array_keys($ress)) && !in_array($_POST['r_name'], array_keys($prods))) { $this->output('maintext', 'Ungültiger Rohstoff/Produkt.'); $this->output('options', array('add' => 'Zurück')); return; } $crule->r_name = $_POST['r_name']; $crule->r_type = isset($ress[$_POST['r_name']]) ? 'resource' : 'product'; if (!is_numeric($_POST['r_limit']) || $_POST['r_limit'] < 0) { $this->output('maintext', 'Ungültiges Limit.'); $this->output('options', array('add' => 'Zurück')); return; } $crule->r_limit = $_POST['r_limit']; if (!is_numeric($_POST['r_price']) || $_POST['r_price'] < 0) { $this->output('maintext', 'Ungültiger Preis'); $this->output('options', array('add' => 'Zurück')); return; } $crule->r_price = $_POST['r_price']; if (!preg_match('#([0-9]{1,2})\\.([0-9]{1,2})\\.([0-9]{4})#i', $_POST['until'], $m)) { $this->output('maintext', 'Das angegebene Ablaufdatum ist ungültig!.'); $this->output('options', array('add' => 'Zurück')); return; } $exp = mktime(date("H"), date("i"), date("s"), $m[2], $m[1], $m[3]); if ($exp < time() || $exp - time() > 60 * 24 * 3600) { $this->output('maintext', 'Das angegebene Ablaufdatum ist nicht in einem Zeitraum von 60 Tagen!'); $this->output('options', array('add' => 'Zurück')); return; } $premium = R::findOne('user_premium', ' user_id = ?', array($this->user->id)); if ($exp > $premium->until) { $this->output('maintext', 'Das angegebene Ablaufdatum ist nach dem Ablaufen deines Premiumaccounts! Dieser läuft ab am: ' . date('d.m.Y - H:i:s', $premium->until)); $this->output('options', array('add' => 'Zurück')); return; } $crule->until = $exp; R::store($crule); R::associate($crule, $this->myCompany); $this->output('maintext', 'Die Regel wurde gespeichert.'); $this->output('options', array('show' => 'Zurück')); return; } $r = array(); $p = array_merge(Config::getConfig('resources'), Config::getConfig('products')); foreach ($p as $k => $px) { if (!isset($px["needs"])) { continue; } $r[$k] = $k; } $this->output('form', array('target' => 'add', 'elements' => array(array('desc' => 'Aktion', 'name' => 'action', 'type' => 'select', 'options' => array('buy' => 'Kaufen', 'sell' => 'Verkaufen')), array('desc' => 'Rohstoff/Produkt', 'name' => 'r_name', 'type' => 'select', 'options' => $r), array('desc' => 'Limit (Beim Verkaufen wird verkauft, sobald das Lager dieses Limit übersteigt. Beim Kaufen wird gekauft sobald das Lager unter dieses Limit sinkt.)', 'name' => 'r_limit', 'type' => 'text', 'value' => '0'), array('desc' => 'Preis pro VE', 'name' => 'r_price', 'type' => 'text', 'value' => '0'), array('desc' => 'Diese Regel ist gültig bis', 'name' => 'until', 'type' => 'date')))); $this->output('options', array('show' => 'Zurück')); }
/** * Makes a copy of a bean. This method copies the bean and * adds the specified associations. * * For instance: R::copy( $book, "author,library" ); * * Duplicates the $book bean and copies the association links * author and library as well. Note that only many-to-many * associations can be copied. Also note that no author or library * beans are copied, only the connections or references to these * beans. * * @param RedBean_OODBBean $bean * @param string $associatedBeanTypesStr * @return array $copiedBean */ public static function copy($bean, $associatedBeanTypesStr) { $type = $bean->getMeta("type"); $copy = R::dispense($type); $copy->import($bean->export()); $copy->copyMetaFrom($bean); $copy->id = 0; R::store($copy); $associatedBeanTypes = explode(",", $associatedBeanTypesStr); foreach ($associatedBeanTypes as $associatedBeanType) { $assocBeans = R::related($bean, $associatedBeanType); foreach ($assocBeans as $assocBean) { R::associate($copy, $assocBean); } } $copy->setMeta("original", $bean); return $copy; }
/** * Test areRelated(). * * @return void */ public function testAreRelatedAndVariations() { $sheep = R::dispense('sheep'); $sheep->name = 'Shawn'; $sheep2 = R::dispense('sheep'); $sheep2->name = 'Billy'; $sheep3 = R::dispense('sheep'); $sheep3->name = 'Moo'; R::store($sheep3); R::associate($sheep, $sheep2); asrt(R::areRelated($sheep, $sheep2), TRUE); R::exec('DELETE FROM sheep_sheep WHERE sheep2_id = ? -- keep-cache', array($sheep2->id)); asrt(R::areRelated($sheep, $sheep2), FALSE); // Use cache? R::associate($sheep, $sheep2); R::$writer->setUseCache(TRUE); asrt(R::areRelated($sheep, $sheep2), TRUE); R::exec('DELETE FROM sheep_sheep WHERE sheep2_id = ? -- keep-cache', array($sheep2->id)); asrt(R::areRelated($sheep, $sheep2), TRUE); // Use cache? R::associate($sheep, $sheep2); asrt(R::areRelated($sheep, $sheep3), FALSE); $pig = R::dispense('pig'); asrt(R::areRelated($sheep, $pig), FALSE); R::freeze(TRUE); asrt(R::areRelated($sheep, $pig), FALSE); R::freeze(FALSE); $foo = R::dispense('foo'); $bar = R::dispense('bar'); $foo->id = 1; $bar->id = 2; asrt(R::areRelated($foo, $bar), FALSE); }
/** * Misc Test relations... * * @return void */ public function testRelationsVariation() { $track = R::dispense('track'); $album = R::dispense('cd'); $track->name = 'a'; $track->ordernum = 1; $track2 = R::dispense('track'); $track2->ordernum = 2; $track2->name = 'b'; R::associate($album, $track); R::associate($album, $track2); $tracks = R::related($album, 'track'); $track = array_shift($tracks); $track2 = array_shift($tracks); $ab = $track->name . $track2->name; asrt($ab == 'ab' || $ab == 'ba', TRUE); $t = R::dispense('person'); $s = R::dispense('person'); $s2 = R::dispense('person'); $t->name = 'a'; $t->role = 'teacher'; $s->role = 'student'; $s2->role = 'student'; $s->name = 'a'; $s2->name = 'b'; $role = R::$writer->esc('role'); R::associate($t, $s); R::associate($t, $s2); $students = R::related($t, 'person', sprintf(' %s = ? ', $role), array("student")); $s = array_shift($students); $s2 = array_shift($students); asrt($s->name == 'a' || $s2->name == 'a', TRUE); asrt($s->name == 'b' || $s2->name == 'b', TRUE); // Empty classroom R::clearRelations($t, 'person'); R::associate($t, $s2); $students = R::related($t, 'person', sprintf(' %s = ? ', $role), array("student")); asrt(count($students), 1); $s = reset($students); asrt($s->name, 'b'); }