public function show_Show() { if (!$this->user->hasPremium()) { $this->error('Nur für Premiumaccounts.'); } $o = '<h3>Aktuelle Lagerverwaltungs-Regeln</h3>'; $o .= '<table class="ordered"> <tr> <th>Aktion</th> <th>Ressource/Produkt</th> <th>Lager-Limit</th> <th>Preis pro VE</th> <th>Gültig bis</th> <th></th> </tr>'; $show = R::related($this->myCompany, 'crule'); foreach ($show as $s) { $o .= '<tr> <td>' . ($s->action == 'buy' ? 'Kaufen' : 'Verkaufen') . '</td> <td>{' . ($s->r_type == 'resource' ? 'r' : 'p') . '_' . $s->r_name . '}</td> <td>' . ($s->action == 'buy' ? '<' : '>') . ' ' . formatCash($s->r_limit) . '</td> <td>' . formatCash($s->r_price) . ' {money}</td> <td>' . date('d.m.Y - H:i:s', $s->until) . '</td> <td><a href="#cancel/' . $s->id . '">{cross title="Stornieren"}</a></td> </tr>'; } $o .= '</table>'; $this->output('maintext', $o); $this->output('options', array('add' => 'Neue Regel hinzufügen')); }
/** * Various. * Various test for OCI. Some basic test cannot be performed because * practical issues (configuration testing VM image etc..). * * @return void */ public function testOCIVaria() { $village = R::dispense('village'); $village->name = 'Lutry'; $id = R::store($village); $village = R::load('village', $id); asrt($village->name, 'Lutry'); list($mill, $tavern) = R::dispense('building', 2); $village->ownBuilding = array($mill, $tavern); //replaces entire list $id = R::store($village); asrt($id, 1); $village = R::load('village', $id); asrt(count($village->ownBuilding), 2); $village2 = R::dispense('village'); $army = R::dispense('army'); $village->sharedArmy[] = $army; $village2->sharedArmy[] = $army; R::store($village); $id = R::store($village2); $village = R::load('village', $id); $army = $village->sharedArmy; $myVillages = R::related($army, 'village'); asrt(count($myVillages), 2); echo PHP_EOL; }
/** * Constructs a new RedBeanModels which is a collection of classes extending model. * The models are created lazily. * Models are only constructed with beans by the model. Beans are * never used by the application directly. */ public function __construct(RedBean_OODBBean $bean, $modelClassName) { assert('is_string($modelClassName)'); assert('$modelClassName != ""'); $this->modelClassName = $modelClassName; $tableName = RedBeanModel::getTableName($modelClassName); $this->bean = $bean; $this->relatedBeansAndModels = array_values(R::related($this->bean, $tableName)); }
public function init() { parent::init(); $this->myQuests = R::related($this->user, 'company_quest'); if (!R::findOne('company', ' user_id = ?', array($this->user->id))) { $this->error('Du besitzt keine Firma. Geh ins Nachbargebäude und gründe dort eine Firma bevor du Aufträge annehmen kannst.'); } }
/** * Returns all the domains that does not have an owner and is of type: name * * @return array Contains Domain Beans * @author Henrik Farre <*****@*****.**> **/ function getUnrelatedMainDomains() { $allDomains = R::find('domain'); $unrelatedDomains = array(); foreach ($allDomains as $domain) { $relations = array(); $relations = R::related($domain, 'owner'); if (empty($relations)) { $unrelatedDomains[] = $domain; } } return $unrelatedDomains; }
public function init() { parent::init(); $this->company = R::findOne('company', ' user_id = ?', array($this->user->id)); if ($this->company) { $this->company_ress = R::findOne('company_ress', 'company_id = ?', array($this->company->id)); $this->company_products = R::findOne('company_products', 'company_id = ?', array($this->company->id)); $this->company_machines = R::findOne('company_machines', 'company_id = ?', array($this->company->id)); $this->initRess(); $this->quests_running = R::related($this->user, 'company_quest', ' completed = 0'); $this->quests_complete = R::related($this->user, 'company_quest', ' completed = 1'); } }
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); }
/** * Constructs a new RedBeanModels which is a collection of classes extending model. * The models are created lazily. * Models are only constructed with beans by the model. Beans are * never used by the application directly. */ public function __construct(RedBean_OODBBean $bean, $modelClassName, $linkType, $linkName = null) { assert('is_string($modelClassName)'); assert('$modelClassName != ""'); assert('is_int($linkType)'); assert('is_string($linkName) || $linkName == null'); assert('($linkType == RedBeanModel::LINK_TYPE_ASSUMPTIVE && $linkName == null) || ($linkType == RedBeanModel::LINK_TYPE_SPECIFIC && $linkName != null)'); $this->modelClassName = $modelClassName; $tableName = RedBeanModel::getTableName($modelClassName); $this->bean = $bean; $this->linkName = $linkName; if ($this->bean->id > 0) { $this->relatedBeansAndModels = array_values(R::related($this->bean, $tableName, null, array(), $this->getTableName(R::dispense($tableName)))); } else { $this->relatedBeansAndModels = array(); } }
public function beforeRender() { parent::beforeRender(); $listsAvailable = R::find('list'); $html = ''; foreach ($listsAvailable as $l) { $html .= "<option value='{$l->id}'>{$l->name}</option>"; } $this->listsAvailable = $html; $user = self::getUser(); if (!($user && $user->id)) { return; } $inLists = R::related($user, 'list'); $html = ''; foreach ($inLists as $l) { $html .= "<li value='{$l->id}'>{$l->name}</li>"; } $this->inLists = "<ul>{$html}</ul>"; }
echo '</td>'; break; case 'uptime': echo '<td class="' . $key . '">' . ($server->{$key} > 0 ? (int) ($server->{$key} / 60 / 60 / 24) . ' days' : '') . '</td>'; break; case 'os': echo '<td class="os ' . strtolower($server->os) . '">' . $server->os . '</td>'; break; case 'cpu_count': echo '<td class="hardware cpu' . ($hardware['cpucount'] ? '' : ' error') . '">' . ($hardware['cpucount'] ?: '<span class="error">?</span>') . '</td>'; break; case 'memory': echo '<td class="hardware memory' . (empty($hardware['memory']) ? ' error' : '') . '">' . (empty($hardware['memory']) ? '?' : $hardware['memory']) . '</td>'; break; case 'drives': $drives = R::related($server, 'drive'); echo '<td class="hardware drives">'; if (!empty($drives)) { foreach ($drives as $d) { echo '<div class="tooltip_trigger"><img src="/design/desktop/images/' . ($d->type == 'harddrive' ? 'harddrive' : 'drive-cdrom') . '.png" class="icon"/></div> <div class="tooltip"> ' . $d->brand . '<br/> Model: ' . $d->model . '<br/> Serial: ' . $d->serial_no . '<br/> Firmware: ' . $d->fw_revision . '</div>'; } } echo '</td>'; break; case 'partitions': echo '<td class="hardware partitions">';
/** * 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'); }
/** * Searches for owners (accounts assigned to domains) * * @return array * @author Henrik Farre <*****@*****.**> **/ private function ownerSearch($str) { $finalResults = array(); $initialResults = R::find('owner', 'name LIKE ?', array($str)); foreach ($initialResults as $result) { $domains = R::related($result, 'domain'); $str = ''; foreach ($domains as $domain) { $str .= $domain->name . '<br/>'; } $formattedResult = array('id' => $result->id, 'label' => $result->name, 'type' => $this->type, 'desc' => '<tr><td></td><td>' . $result->name . '</td><td>' . $str . '</td></tr>'); $finalResults[] = $formattedResult; } return $finalResults; }
//delete without init asrt(R::count('topic'), 3); unset($book->sharedTopic[1]); $id = R::store($book); asrt(R::count('topic'), 3); asrt(count($book->sharedTopic), 1); asrt(count($book2->sharedTopic), 0); //add same topic to other book $book2->sharedTopic[] = $topic3; asrt(count($book2->sharedTopic), 1); $id2 = R::store($book2); asrt(count($book2->sharedTopic), 1); $book2 = R::load('book', $id2); asrt(count($book2->sharedTopic), 1); //get books for topic asrt(count(R::related($topic3, 'book')), 2); $t3 = R::load('topic', $topic3->id); asrt(count($t3->sharedBook), 2); //nuke an own-array, replace entire array at once without getting first $page2->id = 0; $page2->title = 'yet another page 2'; $page4->id = 0; $page4->title = 'yet another page 4'; $book = R::load('book', $id); $book->ownPage = array($page2, $page4); R::store($book); $book = R::load('book', $id); asrt(count($book->ownPage), 2); asrt(reset($book->ownPage)->title, 'yet another page 2'); asrt(end($book->ownPage)->title, 'yet another page 4'); testids($book->ownPage);
public function related($bean, $type, $sql = ' true ', $values = array()) { return R::related($bean, $type, $sql, $values); }
$s->role = 'student'; $s2->role = 'student'; $s->name = 'a'; $s2->name = 'b'; R::associate($t, $s); R::associate($t, $s2); $students = R::related($t, 'person', ' "role" = ? ORDER BY "name" ', array("student")); $s = array_shift($students); $s2 = array_shift($students); asrt($s->name, 'a'); asrt($s2->name, 'b'); $s = R::relatedOne($t, 'person', ' role = ? ORDER BY "name" ', array("student")); asrt($s->name, 'a'); //empty classroom R::clearRelations($t, 'person', $s2); $students = R::related($t, 'person', ' role = ? ORDER BY "name" ', array("student")); asrt(count($students), 1); $s = reset($students); asrt($s->name, 'b'); function getList($beans, $property) { $items = array(); foreach ($beans as $bean) { $items[] = $bean->{$property}; } sort($items); return implode(",", $items); } testpack("unrelated"); $pdo->Execute("DROP TABLE person_person"); $pdo->Execute("DROP TABLE person");
public function accountGroups($account) { return R::related($account, 'group'); }
protected function actionDetails($action, $name, $rp) { if (!isset($rp[$name]) || !isset($rp[$name]["needs"])) { $this->output('maintext', 'Diese Seite ist ungültig!'); return; } $details = $rp[$name]; $type = is_array($details["needs"][0]) ? 'p' : 'r'; if ($this->get(3) != '') { $do = $this->get(3); $id = $this->get(4); if ($id != '') { if (!(is_numeric($this->get(4)) && $this->get(4) > 0)) { $this->error("Invalid ID!"); } } $func = "action" . ucfirst($do); $this->{$func}($action, $name, $details, $type, $id); return; } $own_orders = ''; //$oOrders = R::find('order', ' type = ? AND r_name = ?', array($action, $name)); $oOrders = R::related($this->myCompany, 'order', ' type = ? AND r_name = ?', array($action, $name)); foreach ($oOrders as $o) { $own_orders .= '<tr> <td>' . formatCash($o->r_amount) . '</td> <td>' . formatCash($o->price) . ' {money}</td> <td>' . date('d.m.Y - H:i:s', $o->date + 3 * 24 * 3600) . '</td> <td>' . ($o->automatic == 1 ? '{tick} <i>' . ($o->a_expires == 0 ? '(unbegrenzt)' : '(bis zum ' . date('d.m.Y - H:i:s', $o->a_expires) . ' Uhr)') . '</i>' : '{cross}') . '</td> <td><a href="#action/' . $action . '/' . $name . '/edit/' . $o->id . '">{pencil title="Bearbeiten"}</a></td> <td><a href="#action/' . $action . '/' . $name . '/delete/' . $o->id . '">{bin title="Löschen"}</a></td> </tr>'; } $forgein_orders = ''; try { //$nOrders = @R::unrelated($this->myCompany, 'order', ' type = ? AND r_name = ?', array(($action == "buy" ? "sell" : "buy"), $name)); $nOrders = R::getAll('SELECT `order`.`r_amount` as r_amount, `order`.`price` as price, `order`.`id` as id, `company`.name as name FROM `order`, company_order, company WHERE company_order.company_id != ? AND `order`.id = company_order.order_id AND company.id = company_order.company_id AND `order`.type = ? AND `order`.r_name = ?', array($this->myCompany->getID(), $action == "buy" ? "sell" : "buy", $name)); } catch (Exception $e) { //$forgein_orders .= '<!-- Error: ' .$e->getMessage(). ' -->'; $nOrders = array(); } foreach ($nOrders as $o) { $forgein_orders .= '<tr> <td>' . formatCash($o["r_amount"]) . '</td> <td>' . formatCash($o["price"]) . ' {money}</td> <td>' . htmlspecialchars($o["name"]) . '</td> <td><a href="#action/' . $action . '/' . $name . '/m/' . $o["id"] . '">{briefcase title="Details"}</a></td> </tr>'; } $mp = R::getCell('SELECT `value` FROM market_price WHERE `type` = ? AND `name` = ?', array($action, $name)); $this->output('maintext', '<h3>{' . $type . '_' . $name . '} ' . ($action == "buy" ? "kaufen" : "verkaufen") . '</h3> <p>Aktueller Marktpreis: <b>' . formatCash($mp) . ' {money}</b><br /> Aktueller Kontostand der Firma: <b>' . formatCash($this->myCompany->balance) . ' {money}</b> <br /> Verfügbarkeit im Lager deiner Firma: <b>' . formatCash($type == 'r' ? $this->myRess->{$name} : $this->myProducts->{$name}) . ' VE</b></p> <h4>Fremde ' . ($action == "buy" ? "Verkauforder" : "Kauforder") . '</h4> <table class="ordered"> <tr> <th>Menge</th> <th>Preis pro VE</th> <th>Verkäufer</th> <th></th> </tr> ' . $forgein_orders . ' </table> <br /> <h4>Eigene ' . ($action == "buy" ? "Kauforder" : "Verkauforder") . '</h4> <table class="ordered"> <tr> <th>Menge</th> <th>Preis pro VE</th> <th>Läuft bis</th> <th>automatisch erneuern?</th> <th></th> <th></th> </tr> ' . $own_orders . ' </table> <br /> <h4>Neue ' . ($action == "buy" ? "Kauforder" : "Verkauforder") . ' erstellen</h4>'); $el = array(); $el[] = array('desc' => 'Menge', 'name' => 'amount', 'type' => 'text'); $el[] = array('desc' => 'Preis pro VE', 'name' => 'price', 'type' => 'text'); if ($this->user->hasPremium()) { $el[] = array('desc' => 'automatisch erneuern?', 'name' => 'automatic', 'type' => 'checkbox'); $el[] = array('desc' => 'Autmatisch erneuern bis:', 'name' => 'a_expires', 'type' => 'date'); } $this->output('form', array('target' => 'action/' . $action . '/' . $name . '/create', 'elements' => $el)); }
/** * 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); }
foreach ($domains as $domain) { $owners = array(); $owners = R::related($domain, 'owner'); $ownerString = ''; foreach ($owners as $owner) { $ownerString .= '<a href="' . sprintf(mvc\retrieve('config')->sugarAccountUrl, $owner->account_id) . '">' . $owner->name . '</a> '; } $vhostEntries = R::find('vhostEntry', 'domain_id = ?', array($domain->id)); $servers = array(); foreach ($vhostEntries as $entry) { $server = $linker->getBean($entry, 'server'); $servers[] = $server->name; } $ips = array(); $ipString = ''; $ipAddresses = R::related($domain, 'ip_address'); if (!empty($ipAddresses)) { foreach ($ipAddresses as $ip) { $ips[] = $ip->value; } $ipString = implode(', ', $ips); } echo '<tr> <td><a href="http://' . $domain->name . '">' . $domain->name . '</a></td> <td>' . $ownerString . '</td> <td>' . implode(', ', $servers) . '</td> <td>' . $ipString . '</td> <td>' . $domain->tld . '</td> </tr>'; } ?>
asrt(setget("false"), "false"); asrt(setget("null"), "null"); asrt(setget("NULL"), "NULL"); asrt(setget(null), null); asrt(setget(0) == 0, true); asrt(setget(1) == 1, true); asrt(setget(true) == true, true); asrt(setget(false) == false, true); testpack("test optimization related() "); R::$writer->setBeanFormatter(new TestFormatter()); $book = R::dispense("book"); $book->title = "ABC"; $page = R::dispense("page"); $page->content = "lorem ipsum 123 ... "; R::associate($book, $page); asrt(count(R::related($book, "page", " content LIKE '%123%' ")), 1); testpack("test cooker"); $post = array("book" => array("type" => "book", "title" => "programming the C64"), "book2" => array("type" => "book", "id" => 1, "title" => "the art of doing nothing"), "book3" => array("type" => "book", "id" => 1), "associations" => array(array("book-book2"), array("page:2-book"), array("0"))); $beans = R::cooker($post); asrt(count($beans["can"]), 3); asrt(count($beans["pairs"]), 2); asrt($beans["can"]["book"]->getMeta("tainted"), true); asrt($beans["can"]["book2"]->getMeta("tainted"), true); asrt($beans["can"]["book3"]->getMeta("tainted"), false); asrt($beans["can"]["book3"]->title, "ABC"); asrt($beans["pairs"][0][0]->title, "programming the C64"); testpack("test views"); class Fm implements RedBean_IBeanFormatter { public function formatBeanTable($table) {
/** * 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; }
public function exec($params) { $data = array(); $methods = array('domains.list' => function ($request) { if (isset($request->params['filter'])) { } else { $data['domains'] = R::find('domain'); ob_start(); mvc\render('design/desktop/templates/domains.tpl.php', $data); $html = ob_get_clean(); } $request->returnResult(array('html' => $html, 'callbacks' => array('display.content', 'table.sorter'))); return true; }, 'data.backup' => function ($request) { $owners = R::find('owner'); foreach ($owners as $owner) { $related = R::related($owner, 'domain'); $backup = R::dispense('backup'); $backup->type = "owner_to_domain"; $domains = array(); foreach ($related as $rel) { $domains[] = $rel->name; } $backup->data = serialize(array('owner_name' => $owner->name, 'owner_account_id' => $owner->account_id, 'domains' => $domains)); R::store($backup); } $request->returnResult(array('html' => 'ok')); return true; }, 'data.restore' => function ($request) { $backups = R::find('backup'); foreach ($backups as $backup) { switch ($backup->type) { case 'owner_to_domain': $data = unserialize($backup->data); $owner = R::findOne('owner', 'account_id = ?', array($data['owner_account_id'])); if (!$owner instanceof RedBean_OODBBean) { $owner = R::dispense('owner'); $owner->account_id = $data['owner_account_id']; } $owner->name = $data['owner_name']; /*foreach ( $data['domains'] as $domain ) { $domain ; }*/ R::store($owner); break; } } $request->returnResult(array('html' => 'ok')); return true; }, 'demo.substract' => function ($request) { if (!is_array($request->params)) { $request->returnError(-32602); return FALSE; } $tmp = array_keys($request->params); if (!count($request->params) == 2 || !is_numeric($request->params[array_pop($tmp)]) || !is_numeric($request->params[array_pop($tmp)])) { $request->returnError(-32602); return False; } $request->returnResult(intval($request->params[0]) - intval($request->params[1])); return TRUE; }); $proxy = new Tivoka_ServerArrayHost($methods); $server = new Tivoka_ServerServer($proxy); $server->process(); }
<?php /* * Finds domains that exists on more than 1 server */ $config = (require 'config.php'); require 'includes/redbean/rb.php'; $dsn = 'mysql:host=' . $config->dbHost . ';dbname=' . $config->dbName; R::setup($dsn, $config->dbUsername, $config->dbPassword); $domains = R::find('domain', 'is_active = 1'); foreach ($domains as $domain) { $related = R::related($domain, 'server'); if (sizeof($related) > 1) { echo "\n" . $domain->name . " exists on:\n"; foreach ($related as $server) { echo $server->name . "\n"; } } }
/** * Test basic and complex common usage scenarios for * relations and associations. * * @return void */ public function testScenarios() { list($q1, $q2) = R::dispense('quote', 2); list($pic1, $pic2) = R::dispense('picture', 2); list($book, $book2, $book3) = R::dispense('book', 4); list($topic1, $topic2, $topic3, $topic4, $topic5) = R::dispense('topic', 5); list($page1, $page2, $page3, $page4, $page5, $page6, $page7) = R::dispense('page', 7); $q1->text = 'lorem'; $q2->text = 'ipsum'; $book->title = 'abc'; $book2->title = 'def'; $book3->title = 'ghi'; $page1->title = 'pagina1'; $page2->title = 'pagina2'; $page3->title = 'pagina3'; $page4->title = 'pagina4'; $page5->title = 'pagina5'; $page6->title = 'cover1'; $page7->title = 'cover2'; $topic1->name = 'holiday'; $topic2->name = 'cooking'; $topic3->name = 'gardening'; $topic4->name = 'computing'; $topic5->name = 'christmas'; // Add one page to the book $book->ownPage[] = $page1; $id = R::store($book); asrt(count($book->ownPage), 1); asrt(reset($book->ownPage)->getMeta('type'), 'page'); $book = R::load('book', $id); asrt(count($book->ownPage), 1); asrt(reset($book->ownPage)->getMeta('type'), 'page'); // Performing an own addition $book->ownPage[] = $page2; $id = R::store($book); $book = R::load('book', $id); asrt(count($book->ownPage), 2); // Performing a deletion $book = R::load('book', $id); unset($book->ownPage[1]); $id = R::store($book); $book = R::load('book', $id); asrt(count($book->ownPage), 1); asrt(reset($book->ownPage)->getMeta('type'), 'page'); asrt(R::count('page'), 2); //still exists asrt(reset($book->ownPage)->id, '2'); // Doing a change in one of the owned items $book->ownPage[2]->title = 'page II'; $id = R::store($book); $book = R::load('book', $id); asrt(reset($book->ownPage)->title, 'page II'); // Change by reference now... don't copy! $refToPage2 = $book->ownPage[2]; $refToPage2->title = 'page II b'; $id = R::store($book); $book = R::load('book', $id); asrt(reset($book->ownPage)->title, 'page II b'); // Doing all actions combined $book->ownPage[] = $page3; R::store($book); $book = R::load('book', $id); unset($book->ownPage[2]); // And test custom key $book->ownPage['customkey'] = $page4; $book->ownPage[3]->title = "THIRD"; R::store($book); $book = R::load('book', $id); asrt(count($book->ownPage), 2); $p4 = $book->ownPage[4]; $p3 = $book->ownPage[3]; asrt($p4->title, 'pagina4'); asrt($p3->title, 'THIRD'); // Test replacing an element $book = R::load('book', $id); $book->ownPage[4] = $page5; R::store($book); $book = R::load('book', $id); asrt(count($book->ownPage), 2); $p5 = $book->ownPage[5]; asrt($p5->title, 'pagina5'); // Other way around - single bean asrt($p5->book->title, 'abc'); asrt(R::load('page', 5)->book->title, 'abc'); asrt(R::load('page', 3)->book->title, 'abc'); // Add the other way around - single bean $page1->id = 0; $page1->book = $book2; $page1 = R::load('page', R::store($page1)); asrt($page1->book->title, 'def'); $b2 = R::load('book', $id); asrt(count($b2->ownPage), 2); // Remove the other way around - single bean unset($page1->book); R::store($page1); $b2 = R::load('book', $book2->id); asrt(count($b2->ownPage), 0); // Re-add the page $b2->ownPage[] = $page1; R::store($b2); $b2 = R::load('book', $book2->id); asrt(count($b2->ownPage), 1); // Different, less elegant way to remove $page1 = reset($b2->ownPage); $page1->book_id = NULL; R::store($page1); $b2 = R::load('book', $book2->id); asrt(count($b2->ownPage), 0); // Re-add the page $b2->ownPage[] = $page1; R::store($b2); $b2 = R::load('book', $book2->id); asrt(count($b2->ownPage), 1); // Another less elegant way to remove $page1->book = NULL; R::store($page1); $cols = R::getColumns('page'); asrt(isset($cols['book']), FALSE); $b2 = R::load('book', $book2->id); asrt(count($b2->ownPage), 0); // Re-add the page $b2->ownPage[] = $page1; R::store($b2); $b2 = R::load('book', $book2->id); asrt(count($b2->ownPage), 1); // Another less elegant... just plain ugly... way to remove $page1->book = FALSE; R::store($page1); $cols = R::getColumns('page'); asrt(isset($cols['book']), FALSE); $b2 = R::load('book', $book2->id); asrt(count($b2->ownPage), 0); // Re-add the page $b2->ownPage[] = $page1; R::store($b2); $b2 = R::load('book', $book2->id); asrt(count($b2->ownPage), 1); // You are not allowed to re-use the field for something else foreach (array(1, -2.1, array(), TRUE, 'NULL', new stdClass(), 'just a string', array('a' => 1), 0) as $value) { try { $page1->book = $value; fail(); } catch (RedBean_Exception_Security $e) { pass(); } } // Test fk, not allowed to set to 0 $page1 = reset($b2->ownPage); $page1->book_id = 0; // Even uglier way, but still needs to work $page1 = reset($b2->ownPage); $page1->book_id = NULL; R::store($b2); $b2 = R::load('book', $book2->id); asrt(count($b2->ownPage), 0); // Test shared items $book = R::load('book', $id); $book->sharedTopic[] = $topic1; $id = R::store($book); // Add an item asrt(count($book->sharedTopic), 1); asrt(reset($book->sharedTopic)->name, 'holiday'); $book = R::load('book', $id); asrt(count($book->sharedTopic), 1); asrt(reset($book->sharedTopic)->name, 'holiday'); // Add another item $book->sharedTopic[] = $topic2; $id = R::store($book); $tidx = R::store(R::dispense('topic')); $book = R::load('book', $id); asrt(count($book->sharedTopic), 2); $t1 = $book->sharedTopic[1]; $t2 = $book->sharedTopic[2]; asrt($t1->name, 'holiday'); asrt($t2->name, 'cooking'); // Remove an item unset($book->sharedTopic[2]); asrt(count($book->sharedTopic), 1); $id = R::store($book); $book = R::load('book', $id); asrt(count($book->sharedTopic), 1); asrt(reset($book->sharedTopic)->name, 'holiday'); // Add and change $book->sharedTopic[] = $topic3; $book->sharedTopic[1]->name = 'tropics'; $id = R::store($book); $book = R::load('book', $id); asrt(count($book->sharedTopic), 2); asrt($book->sharedTopic[1]->name, 'tropics'); testids($book->sharedTopic); R::trash(R::load('topic', $tidx)); $id = R::store($book); $book = R::load('book', $id); // Delete without save unset($book->sharedTopic[1]); $book = R::load('book', $id); asrt(count($book->sharedTopic), 2); $book = R::load('book', $id); // Delete without init asrt(R::count('topic'), 3); unset($book->sharedTopic[1]); $id = R::store($book); asrt(R::count('topic'), 3); asrt(count($book->sharedTopic), 1); asrt(count($book2->sharedTopic), 0); // Add same topic to other book $book2->sharedTopic[] = $topic3; asrt(count($book2->sharedTopic), 1); $id2 = R::store($book2); asrt(count($book2->sharedTopic), 1); $book2 = R::load('book', $id2); asrt(count($book2->sharedTopic), 1); // Get books for topic asrt(count(R::related($topic3, 'book')), 2); asrt(R::relatedOne($topic3, 'book') instanceof RedBean_OODBBean, TRUE); $items = R::related($topic3, 'book'); $a = reset($items); asrt(R::relatedOne($topic3, 'book')->id, $a->id); $t3 = R::load('topic', $topic3->id); asrt(count($t3->sharedBook), 2); asrt(R::relatedOne($topic3, 'nothingness'), NULL); // Testing relatedLast $z = end($items); asrt(R::relatedLast($topic3, 'book')->id, $z->id); asrt(R::relatedLast($topic3, 'manuscript'), NULL); // Nuke an own-array, replace entire array at once without getting first $page2->id = 0; $page2->title = 'yet another page 2'; $page4->id = 0; $page4->title = 'yet another page 4'; $book = R::load('book', $id); $book->ownPage = array($page2, $page4); R::store($book); $book = R::load('book', $id); asrt(count($book->ownPage), 2); asrt(reset($book->ownPage)->title, 'yet another page 2'); asrt(end($book->ownPage)->title, 'yet another page 4'); testids($book->ownPage); // Test with alias format $book3->cover = $page6; $idb3 = R::store($book3); $book3 = R::load('book', $idb3); $justACover = $book3->fetchAs('page')->cover; asrt($book3->cover instanceof RedBean_OODBBean, TRUE); asrt($justACover->title, 'cover1'); // No page property asrt(isset($book3->page), FALSE); // Test doubling and other side effects ... should not occur.. $book3->sharedTopic = array($topic1, $topic2); $book3 = R::load('book', R::store($book3)); $book3->sharedTopic = array(); $book3 = R::load('book', R::store($book3)); asrt(count($book3->sharedTopic), 0); $book3->sharedTopic[] = $topic1; $book3 = R::load('book', R::store($book3)); // Added only one, not more? asrt(count($book3->sharedTopic), 1); asrt(intval(R::getCell("select count(*) from book_topic where book_id = {$idb3}")), 1); // Add the same $book3->sharedTopic[] = $topic1; $book3 = R::load('book', R::store($book3)); asrt(count($book3->sharedTopic), 1); asrt(intval(R::getCell("select count(*) from book_topic where book_id = {$idb3}")), 1); $book3->sharedTopic['differentkey'] = $topic1; $book3 = R::load('book', R::store($book3)); asrt(count($book3->sharedTopic), 1); asrt(intval(R::getCell("select count(*) from book_topic where book_id = {$idb3}")), 1); // Ugly assign, auto array generation $book3->ownPage[] = $page1; $book3 = R::load('book', R::store($book3)); asrt(count($book3->ownPage), 1); asrt(intval(R::getCell("select count(*) from page where book_id = {$idb3} ")), 1); $book3 = R::load('book', $idb3); $book3->ownPage = array(); // No change until saved asrt(intval(R::getCell("select count(*) from page where book_id = {$idb3} ")), 1); $book3 = R::load('book', R::store($book3)); asrt(intval(R::getCell("select count(*) from page where book_id = {$idb3} ")), 0); asrt(count($book3->ownPage), 0); $book3 = R::load('book', $idb3); /** * Why do I need to do this ---> why does trash() not set id -> 0? * Because you unset() so trash is done on origin not bean */ $page1->id = 0; $page2->id = 0; $page3->id = 0; $book3->ownPage[] = $page1; $book3->ownPage[] = $page2; $book3->ownPage[] = $page3; $book3 = R::load('book', R::store($book3)); asrt(intval(R::getCell("select count(*) from page where book_id = {$idb3} ")), 3); asrt(count($book3->ownPage), 3); unset($book3->ownPage[$page2->id]); $book3->ownPage[] = $page3; $book3->ownPage['try_to_trick_ya'] = $page3; $book3 = R::load('book', R::store($book3)); asrt(intval(R::getCell("select count(*) from page where book_id = {$idb3} ")), 2); asrt(count($book3->ownPage), 2); // Delete and re-add $book3 = R::load('book', $idb3); unset($book3->ownPage[10]); $book3->ownPage[] = $page1; $book3 = R::load('book', R::store($book3)); asrt(count($book3->ownPage), 2); $book3 = R::load('book', $idb3); unset($book3->sharedTopic[1]); $book3->sharedTopic[] = $topic1; $book3 = R::load('book', R::store($book3)); asrt(count($book3->sharedTopic), 1); // Test performance $logger = RedBean_Plugin_QueryLogger::getInstanceAndAttach(R::$adapter); $book = R::load('book', 1); $book->sharedTopic = array(); R::store($book); // No more than 1 update asrt(count($logger->grep('UPDATE')), 1); $book = R::load('book', 1); $logger->clear(); print_r($book->sharedTopic, 1); // No more than 1 select asrt(count($logger->grep('SELECT')), 1); $logger->clear(); $book->sharedTopic[] = $topic1; $book->sharedTopic[] = $topic2; asrt(count($logger->grep('SELECT')), 0); R::store($book); $book->sharedTopic[] = $topic3; // Now do NOT clear all and then add one, just add the one $logger->clear(); R::store($book); $book = R::load('book', 1); asrt(count($book->sharedTopic), 3); // No deletes asrt(count($logger->grep("DELETE FROM")), 0); $book->sharedTopic['a'] = $topic3; unset($book->sharedTopic['a']); R::store($book); $book = R::load('book', 1); asrt(count($book->sharedTopic), 3); // No deletes asrt(count($logger->grep("DELETE FROM")), 0); $book->ownPage = array(); R::store($book); asrt(count($book->ownPage), 0); $book->ownPage[] = $page1; $book->ownPage['a'] = $page2; asrt(count($book->ownPage), 2); R::store($book); unset($book->ownPage['a']); asrt(count($book->ownPage), 2); unset($book->ownPage[11]); R::store($book); $book = R::load('book', 1); asrt(count($book->ownPage), 1); $aPage = $book->ownPage[10]; unset($book->ownPage[10]); $aPage->title .= ' changed '; $book->ownPage['anotherPage'] = $aPage; $logger->clear(); R::store($book); // if ($db=="mysql") asrt(count($logger->grep("SELECT")),0); $book = R::load('book', 1); asrt(count($book->ownPage), 1); $ap = reset($book->ownPage); asrt($ap->title, "pagina1 changed "); // Fix udiff instead of diff $book3->ownPage = array($page3, $page1); $i = R::store($book3); $book3 = R::load('book', $i); asrt(intval(R::getCell("select count(*) from page where book_id = {$idb3} ")), 2); asrt(count($book3->ownPage), 2); $pic1->name = 'aaa'; $pic2->name = 'bbb'; R::store($pic1); R::store($q1); $book3->ownPicture[] = $pic1; $book3->ownQuote[] = $q1; $book3 = R::load('book', R::store($book3)); // two own-arrays -->forgot array_merge asrt(count($book3->ownPicture), 1); asrt(count($book3->ownQuote), 1); asrt(count($book3->ownPage), 2); $book3 = R::load('book', R::store($book3)); unset($book3->ownPicture[1]); $book3 = R::load('book', R::store($book3)); asrt(count($book3->ownPicture), 0); asrt(count($book3->ownQuote), 1); asrt(count($book3->ownPage), 2); $book3 = R::load('book', R::store($book3)); $NOTE = 0; $quotes = R::dispense('quote', 10); foreach ($quotes as &$justSomeQuote) { $justSomeQuote->note = 'note' . ++$NOTE; } $pictures = R::dispense('picture', 10); foreach ($pictures as &$justSomePic) { $justSomePic->note = 'note' . ++$NOTE; } $topics = R::dispense('topic', 10); foreach ($topics as &$justSomeTopic) { $justSomeTopic->note = 'note' . ++$NOTE; } for ($j = 0; $j < 10; $j++) { // Do several mutations for ($x = 0; $x < rand(1, 20); $x++) { modgr($book3, $quotes, $pictures, $topics); } $qbefore = count($book3->ownQuote); $pbefore = count($book3->ownPicture); $tbefore = count($book3->sharedTopic); $qjson = json_encode($book->ownQuote); $pjson = json_encode($book->ownPicture); $tjson = json_encode($book->sharedTopic); $book3 = R::load('book', R::store($book3)); asrt(count($book3->ownQuote), $qbefore); asrt(count($book3->ownPicture), $pbefore); asrt(count($book3->sharedTopic), $tbefore); asrt(json_encode($book->ownQuote), $qjson); asrt(json_encode($book->ownPicture), $pjson); asrt(json_encode($book->sharedTopic), $tjson); testids($book->ownQuote); testids($book->ownPicture); testids($book->sharedTopic); } }
public static function tagged($beanType, $tagList) { if ($tagList !== false && !is_array($tagList)) { $tags = explode(",", (string) $tagList); } else { $tags = $tagList; } $collection = array(); foreach ($tags as $tag) { $retrieved = array(); $tag = R::findOne("tag", " title = ? ", array($tag)); if ($tag) { $retrieved = R::related($tag, $beanType); } foreach ($retrieved as $key => $bean) { $collection[$key] = $bean; } } return $collection; }
/** * */ 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'); } }
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; } }
/** * 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'); }
/** * Test some frequently used scenarios. * * @return void */ public function testAssocVariations() { try { R::related(NULL, 'book'); } catch (Exception $e) { asrt($e instanceof RedBean_Exception_Security, TRUE); } try { R::related(100, 'book'); } catch (Exception $e) { asrt($e instanceof RedBean_Exception_Security, TRUE); } try { R::related(array('fakeBean'), 'book'); } catch (Exception $e) { asrt($e instanceof RedBean_Exception_Security, TRUE); } list($r1, $r2, $r3) = R::dispense('reader', 3); $r1->name = 'MrOdd'; $r2->name = 'MrEven'; $r3->name = 'MrAll'; $books = R::dispense('book', 5); $i = 1; foreach ($books as $b) { $b->title = 'b' . $i++; if ($i % 2) { R::associate($b, $r2); } else { R::associate($b, $r1); } } $readersOdd = R::related(array($books[0], $books[2], $books[4]), 'reader'); asrt(count($readersOdd), 1); $readerOdd = reset($readersOdd); asrt($readerOdd->name, 'MrOdd'); $readersEven = R::related(array($books[1], $books[3]), 'reader'); asrt(count($readersEven), 1); $readerEven = reset($readersEven); asrt($readerEven->name, 'MrEven'); foreach ($books as $b) { R::associate($b, $r3); } $readersOdd = R::related(array($books[0], $books[2], $books[4]), 'reader'); asrt(count($readersOdd), 2); $readersEven = R::related(array($books[1], $books[3]), 'reader'); asrt(count($readersEven), 2); $found = 0; foreach ($readersEven as $r) { if ($r->name == 'MrAll') { $found = 1; } } asrt($found, 1); }
/** * enables buy/selling for an npc * @param string $type buy/sell From the view of the NPC * @param string $intoTable into which table should be sold/bought from? * @param string $funcName name of the method this function is called */ protected function dealerNPC($type, $intoTable, $funcName) { if ($this->get(1) == "handle" && is_numeric($this->get(2))) { $itemID = $this->get(2); $maxAmount = 0; $val = 0; if ($type == "sell") { $item = R::findOne('item', ' id = ?', array($itemID)); $val = $item->value; $maxAmount = floor($this->user->cash / $val); } else { $_i = R::findOne('inventory', ' id = ? AND user_id = ?', array($itemID, $this->user->getID())); $item = $_i->item; $val = floor($item->value * NPC_BUY_PRICE); $maxAmount = $_i->amount; } if ($maxAmount == 0) { $this->output("maintext", "Du kannst " . htmlspecialchars($item->name) . " leider nicht " . ($type == "sell" ? "kaufen" : "verkaufen")); $this->output('options', array($funcName => 'Zurück')); return; } if (isset($_POST["amount"]) && is_numeric($_POST["amount"]) && $_POST["amount"] > 0) { $amount = $_POST["amount"]; if ($amount > $maxAmount) { $this->output("maintext", "Du kannst " . htmlspecialchars($item->name) . " nicht " . htmlspecialchars($amount) . "x " . ($type == "sell" ? "kaufen" : "verkaufen")); $this->output('options', array($funcName => 'Zurück')); return; } R::$adapter->startTransaction(); if ($type == "sell") { // sell items to user $inv = R::dispense('inventory'); $inv->amount = $amount; $inv->param = ""; $inv->user = $this->user; $inv->item = $item; R::store($inv); $this->user->cash -= $amount * $val; R::store($this->user); } else { // buy from user $_i->amount -= $amount; if ($_i->amount <= 0) { R::trash($_i); } else { R::store($_i); } $this->user->cash += $amount * $val; R::store($this->user); } R::$adapter->commit(); $this->output("maintext", "Du hast " . htmlspecialchars($item->name) . " erfolgreich " . htmlspecialchars($amount) . "x " . ($type == "sell" ? "gekauft" : "verkauft")); $this->output('options', array('interact' => 'Zurück')); $this->output('speak', 'Danke dir!'); return; } $this->output("maintext", "Wie oft möchtest du " . htmlspecialchars($item->name) . " zu " . $val . " {money} pro Stück\n\t\t\t" . ($type == "sell" ? "kaufen" : "verkaufen") . "? (maximal " . $maxAmount . "x)"); $this->output("form", array("target" => $funcName . "/handle/" . $itemID, "elements" => array(array("desc" => "Anzahl", "name" => "amount", "type" => "text", "value" => 1)))); $this->output('options', array($funcName => 'Zurück')); return; } $this->output("maintext", "Was möchtest du " . ($type == "sell" ? "kaufen" : "verkaufen") . "?"); $o = array(); $listing = array(); if ($type == "sell") { $items = R::related($this->npc, 'item'); foreach ($items as $i) { $listing[] = array('id' => $i->id, 'name' => $i->name, 'amount' => 1, 'value' => $i->value); } } else { $inv = R::find('inventory', ' user_id = ?', array($this->user->getID())); foreach ($inv as $i) { $listing[] = array('id' => $i->id, 'name' => $i->item->name, 'amount' => $i->amount, 'value' => floor(NPC_BUY_PRICE * $i->item->value)); } } foreach ($listing as $l) { $o[$funcName . "/handle/" . $l["id"]] = $l["name"] . " (" . $l["value"] . " {money} pro Item)"; } $o["interact"] = "Zurück"; $this->output('options', $o); }