/**
  * Handles constructing the relatedBeansAndModels with special attention to the case where it is PolyOneToMany
  * @param string $modelClassName
  * @param mixed $sqlOrBean
  */
 private function constructRelatedBeansAndModels($modelClassName, $sqlOrBean = '')
 {
     assert('is_string($sqlOrBean) || $sqlOrBean instanceof RedBean_OODBBean');
     $tableName = RedBeanModel::getTableName($modelClassName);
     if (is_string($sqlOrBean)) {
         $this->relatedBeansAndModels = array_values($beans = R::find($tableName, $sqlOrBean));
     } else {
         assert('$sqlOrBean instanceof RedBean_OODBBean');
         $this->bean = $sqlOrBean;
         try {
             if ($this->bean->id > 0) {
                 if ($this->polyName != null) {
                     $value = array();
                     $values['id'] = $this->bean->id;
                     $values['type'] = $this->bean->getMeta('type');
                     $this->relatedBeansAndModels = array_values(R::find($tableName, strtolower($this->polyName) . '_id = :id AND ' . strtolower($this->polyName) . '_type = :type', $values));
                 } else {
                     $relatedIds = ZurmoRedBeanLinkManager::getKeys($this->bean, $tableName);
                     $this->relatedBeansAndModels = array_values(R::batch($tableName, $relatedIds));
                 }
             } else {
                 $this->relatedBeansAndModels = array();
             }
         } catch (RedBean_Exception_SQL $e) {
             // SQLSTATE[42S02]: Base table or view not found...
             // SQLSTATE[42S22]: Column not found...
             if (!in_array($e->getSQLState(), array('42S02', '42S22'))) {
                 throw $e;
             }
             $this->relatedBeansAndModels = array();
         }
     }
 }
 protected function actionViewConversation()
 {
     // create the user object
     $this->user = $this->setUser($this->request['user']);
     // halt on fail
     if (!$this->user) {
         return;
     }
     // create the receipient object
     $this->receipient = $this->setReceipient($this->request['receipient']);
     // halt on fail
     if (!$this->receipient) {
         return;
     }
     // get the messages between the user and receipient
     $rows = R::find('message', '  (user_id = :user_id AND receipient_id = :receipient_id)
         OR (user_id = :receipient_id AND receipient_id = :user_id)', array(':user_id' => $this->user->id, ':receipient_id' => $this->receipient->id));
     // convert array into bean objects
     $messages = R::convertToBeans('message', $rows);
     // create message objects from bean objects
     $conversation = array();
     foreach ($messages as $id => $message) {
         $conversation[$id] = new Message($message);
     }
     // add them to the data array for output
     $this->data = $conversation;
 }
Esempio n. 3
0
    public function show_Chat()
    {
        $lastMessage = $_POST["time"];
        if ($lastMessage < 0 || !is_numeric($lastMessage)) {
            $this->error('Invalid lastMessage-Timestamp');
        }
        if ($lastMessage < time() - CHAT_LIFETIME) {
            $lastMessage = time() - CHAT_LIFETIME;
        }
        $messages = R::find('chat_message', ' map = ? AND time > ?
		AND ((type = ? || (type = ? AND visible_for_id = ?)) || player_id = ?) ORDER BY time ASC', array($this->mapPosition->map, $lastMessage, 'public', 'private', $this->user->id, $this->user->id));
        $m = array();
        $latest = $lastMessage;
        foreach ($messages as $msg) {
            $to = "";
            $type = $msg->player_id != null && $msg->player_id == $this->user->id ? "own" : $msg->type;
            if ($type == "own" && $msg->visible_for_id != null) {
                $p = R::findOne('user', ' id = ?', array($msg->visible_for_id));
                if ($p != false) {
                    $to = htmlspecialchars($p->username);
                }
            }
            $m[] = array('time' => date("H:i:s", $msg->time), 'author' => htmlspecialchars($msg->author), 'pid' => $msg->player_id != null ? $msg->player_id : "-1", 'text' => $msg->text, 'type' => $type, 'to' => $to);
            $latest = $msg->time;
        }
        $this->output('messages', $m);
        $this->output('timestamp', $latest);
    }
 public static function clean($f3, $filename)
 {
     $total_filesize = R::getCell('select sum(filesize) as total_filesize from cache');
     $cache_total_filesize_limit = $f3->get("UPLOAD.cache_total_size_limit");
     $cache_total_filesize_limit = PFH_File_helper::convert_filesize_in_bytes($cache_total_filesize_limit);
     if ($total_filesize > $cache_total_filesize_limit) {
         $caches = R::find("cache", "ORDER BY datetime");
         $count = count($caches);
         // 只有一個不刪除
         //if ($count < 2) {
         //    return;
         //}
         foreach ($caches as $key => $cache) {
             //不刪除最後一個
             //if ($key > $count - 1) {
             //    return;
             //}
             if ($cache->path === $filename) {
                 continue;
             }
             //throw new Exception("$key $cache->path");
             //echo $cache->path . "<br />";
             if (is_file($cache->path)) {
                 unlink($cache->path);
             }
             $total_filesize = $total_filesize - $cache->filesize;
             R::trash($cache);
             if ($total_filesize < $cache_total_filesize_limit) {
                 break;
             }
         }
     }
 }
 public function exec($params)
 {
     $data = array();
     $module = isset($params['module']) ? $params['module'] : 'servers';
     $view = isset($params['view']) ? $params['view'] : 'index';
     $data['module'] = $module;
     $data['view'] = $view;
     $data['title'] = '';
     $data['uri'] = '/' . $module . '/' . $view;
     $data['uriArray'] = array('/', $module, $view);
     switch ($module) {
         case 'domains':
             $domains = R::find('domain');
             $data['title'] = 'Domains';
             $data['domains'] = $domains;
             $data['template'] = 'design/desktop/templates/domains.tpl.php';
             break;
         case 'accounts':
             $data['title'] = 'Domains to accounts';
             $data['domains'] = getUnrelatedMainDomains();
             $data['template'] = 'design/desktop/templates/accounts.tpl.php';
             break;
         case 'servers':
             $data['title'] = 'Servers';
             $data['hasFieldSelector'] = true;
             $data['avaliableFields'] = getAvaliableFields('servers');
             $data['enabledFields'] = getEnabledFields('servers');
             $data['serversGrouped'] = getGroupedByType();
             $data['template'] = 'design/desktop/templates/servers_list.tpl.php';
             break;
         case 'search':
             $data['title'] = 'Search';
             $data['template'] = 'design/desktop/templates/search.tpl.php';
             break;
         case 'cleanup':
             $data['title'] = 'Cleanup';
             $data['template'] = 'design/desktop/templates/cleanup.tpl.php';
             break;
         default:
             $data['title'] = '404 Page not found';
             $data['template'] = 'design/desktop/templates/error.tpl.php';
             $data['error'] = array('code' => '404', 'msg' => 'Page not found');
             break;
     }
     mvc\render('design/desktop/templates/header.tpl.php', $data);
     mvc\render('design/desktop/templates/top_menu.tpl.php', $data);
     if (isset($data['hasFieldSelector']) && $data['hasFieldSelector']) {
         mvc\render('design/desktop/templates/field_selector.tpl.php', $data);
     }
     if (mvc\retrieve('debug')) {
         $data['values']['params'] = $params;
         mvc\render('design/desktop/templates/debug.tpl.php', $data);
     }
     mvc\render($data['template'], $data);
     mvc\render('design/desktop/templates/footer.tpl.php', $data);
 }
Esempio n. 6
0
 public function show_Inventory()
 {
     $items = R::find('inventory', ' user_id = ?', array($this->user->getID()));
     $i = array();
     foreach ($items as $itm) {
         $item = R::load('inventory', $itm->getID());
         $i[] = array("id" => $item->getID(), "name" => $item->item->name, "desc" => str_replace('{param}', $item->param, $item->item->desc), "is_usable" => $item->item->usable == 1 ? true : false, "value" => $item->item->value, "usable_link" => $item->item->usable_link_desc, "amount" => $item->amount, "type" => $item->item->type);
     }
     $this->output('items', $i);
 }
Esempio n. 7
0
function getall()
{
    try {
        $articles = R::find('articles');
        echo json_encode(R::exportAll($articles));
    } catch (Exception $e) {
        $app->response()->status(400);
        $app->response()->header('X-Status-Reason', $e->getMessage());
    }
}
Esempio n. 8
0
 function index($f3)
 {
     $D = \R::find($this->model_name(), 'ORDER BY displayname ASC');
     if ($D) {
         $f3->set('data', \R::exportAll($D));
     } else {
         $f3->set('data', '');
     }
     show_page($f3, $this->template_name() . '.index');
 }
Esempio n. 9
0
 function totalcount()
 {
     include_once 'dbcon.php';
     $college = R::find('college', 'delflg=?', ['N']);
     $count = 0;
     if ($college != null && !empty($college)) {
         $count = sizeof($college);
     }
     return $count;
 }
Esempio n. 10
0
 /**
  * Return all records for a type
  * @param string $type Database table
  * @return string JSON All of the records and their contents
  * @throws API\Exceptions\APIException No records found, 404
  */
 public static function getList($type)
 {
     $beans = R::find($type);
     $response = R::exportAll($beans);
     if (sizeof($response) > 0) {
         return new JSON(array("data" => $response));
     } else {
         throw new APIException("No " . $type . " records found.", 404);
     }
 }
Esempio n. 11
0
 function totalcount()
 {
     include_once 'dbcon.php';
     $review = R::find('reviews', 'delflg=N');
     $count = 0;
     if ($review != null && !empty($review)) {
         $count = sizeof($review);
     }
     return $count;
 }
Esempio n. 12
0
 private function loadTable()
 {
     $rows = array();
     $r = R::find($this->currentTable, ' 1 ORDER BY id ASC LIMIT 0,30');
     foreach ($r as $row) {
         foreach ($this->dbTables[$this->currentTable] as $field) {
             $rows[$row->getID()][$field] = $row->{$field};
         }
     }
     Framework::TPL()->assign('tableRows', $rows);
 }
Esempio n. 13
0
 public function getMessagesForUser($user_id)
 {
     $messageList = R::find('message', '  recipient_id = ? ', [$user_id], ' ORDER BY date ASC ');
     $messages = array();
     foreach ($messageList as $message) {
         $sender = R::findOne('user', '  id = ? ', [$message->sender_id]);
         $currentElement = array("sender" => $sender->username, "content" => $message->content, "date" => $message->date, "m_id" => $message->id);
         array_push($messages, $currentElement);
     }
     return json_encode($messages);
 }
 /**
  * Given an external system id and model class name, try to find the associated model if it exists. If it is
  * not found, a NotFoundException will be thrown.  Otherwise the model will be made and returned.
  * @param string $id
  * @param string $modelClassName
  */
 public static function getModelByExternalSystemIdAndModelClassName($id, $modelClassName)
 {
     assert('$id != null && is_string($id)');
     assert('is_string($modelClassName)');
     $tableName = $modelClassName::getTableName($modelClassName);
     $beans = R::find($tableName, ExternalSystemIdUtil::EXTERNAL_SYSTEM_ID_COLUMN_NAME . " = '{$id}'");
     assert('count($beans) <= 1');
     if (count($beans) == 0) {
         throw new NotFoundException();
     }
     return RedBeanModel::makeModel(end($beans), $modelClassName);
 }
 /**
  * Handle profile operations /data/xxxx
  *
  * @param object	$context	The context object for the site
  *
  * @return string	A template name
  */
 public function handle($context)
 {
     $data = R::find('file', 'category = "data"');
     // Refine search result if the user searches in the text box
     $searchText = $context->mustpostpar('data_search_text', '');
     if (!empty($searchText)) {
         $searchText = '%' . $searchText . '%';
         $data = R::find('file', 'category like ? and name like ?', ["data", $searchText]);
     }
     $context->local()->addval('data', $data);
     return 'data.twig';
 }
 /**
  * Handle profile operations /code/xxxx
  *
  * @param object	$context	The context object for the site
  *
  * @return string	A template name
  */
 public function handle($context)
 {
     $sourcecode = R::find('file', 'category = "source-code"');
     // Refine search result if the user searches in the text box
     $searchText = $context->mustpostpar('sourcecode_search_text', '');
     if (!empty($searchText)) {
         $searchText = '%' . $searchText . '%';
         $sourcecode = R::find('file', 'category like ? and name like ?', ["source-code", $searchText]);
     }
     $context->local()->addval('sourcecode', $sourcecode);
     return 'sourcecode.twig';
 }
Esempio n. 17
0
 /**
  * Make a confirmation code and store it in the database
  *
  * @param object	$context The context bean
  * @param object	$bn	 A User bean
  * @param string	$kind
  *
  * @return string
  */
 private function makecode($context, $bn, $kind)
 {
     R::trashAll(R::find('confirm', 'user_id=?', array($bn->getID())));
     $code = hash('sha256', $bn->getID . $bn->email . $bn->login . uniqid());
     $conf = R::dispense('confirm');
     $conf->code = $code;
     $conf->issued = $context->utcnow();
     $conf->kind = $kind;
     $conf->user = $bn;
     R::store($conf);
     return $code;
 }
Esempio n. 18
0
 public static function find($type, $sql = "1", $values = array(), $cacheId = "0")
 {
     $cacheName = PATH . '/cache/r_' . sha1('multiple' . $type . $sql . json_encode($values) . $cacheId) . '.rcache';
     if (!file_exists($cacheName)) {
         $data = R::find($type, $sql, $values);
         $fp = fopen($cacheName, 'w');
         fwrite($fp, serialize($data));
         fclose($fp);
         return $data;
     }
     return unserialize(file_get_contents($cacheName));
 }
 function getIndice($idsubmenu)
 {
     //$indices = R::findAll( 'indice', "submenu_id = ?", array($idsubmenu));
     //$indices = R::find( 'indice', "submenu_id = ? ORDER BY id DESC", array($idsubmenu));
     //$indices = R::find( 'indices', "submenu_id = ?", array($idsubmenu));
     //echo $indices;
     //return $indices->export();
     $indices = R::find('indice', ' submenu_id = ? ORDER BY titulo ASC', array($idsubmenu));
     //$indices = R::load( 'indice', 1 );
     //return $indices->exportAll;
     return R::exportAll($indices);
 }
 /**
  * Handle profile operations /apps/xxxx
  *
  * @param object	$context	The context object for the site
  *
  * @return string	A template name
  */
 public function handle($context)
 {
     $apps = R::find('file', 'category = "apps"');
     $searchText = $context->mustpostpar('apps_search_text', '');
     // Refine search result if the user searches in the text box
     if (!empty($searchText)) {
         $searchText = '%' . $searchText . '%';
         $apps = R::find('file', 'category like ? and name like ?', ["apps", $searchText]);
     }
     $context->local()->addval('apps', $apps);
     return 'apps.twig';
 }
Esempio n. 21
0
 /**
  * Test to make sure stash cache works with recursively opening models
  * with FUSE.
  * 
  * @return void
  */
 public function testIssue259()
 {
     testpack('Testing Issue #259 - Stash Cache breaks model delegation in open().');
     $mother = R::dispense('mother');
     $mother->desc = 'I am mother';
     R::store($mother);
     $child = R::dispense('child');
     $child->mother = $mother;
     $child->desc = 'I am child';
     $id = R::store($child);
     R::findOne('child', ' id = ?', array($id));
     R::find('child', ' id = ? ', array($id));
     R::load('child', $id);
 }
Esempio n. 22
0
 function login($username, $password)
 {
     include_once 'dbcon.php';
     $user = R::find('user', ' uname = ?', [$username]);
     // $found = false;
     if (!empty($user)) {
         foreach ($user as $checkuser) {
             $match = strcmp($checkuser->password, $password);
             if ($match == 0) {
                 return $user;
             }
         }
     }
     return false;
 }
Esempio n. 23
0
 function login($username, $password)
 {
     include_once 'dbcon.php';
     $admin = R::find('admin', ' uname = ?', [$username]);
     // $found = false;
     if (!empty($admin)) {
         foreach ($admin as $checkadmin) {
             $match = strcmp($checkadmin->password, $password);
             if ($match == 0) {
                 return $admin;
             }
         }
     }
     return false;
 }
 public function show_Store()
 {
     if ($this->get(1) != "" && is_numeric($this->get(1))) {
         $id = $this->get(1);
         $this->MoveItem($id, "put");
         return;
     }
     $this->output('maintext', 'Welches Item möchtest du abgeben?');
     $o = array();
     $items = R::find('inventory', ' user_id = ?', array($this->user->getID()));
     foreach ($items as $item) {
         $o["store/" . $item->id] = $item->amount . "x " . $item->item->name;
     }
     $o["interact"] = "Zurück";
     $this->output('options', $o);
 }
Esempio n. 25
0
 public function show_Main()
 {
     $usersPerPage = 20;
     $totalUsers = R::getCell('SELECT count(id) FROM user');
     $pages = ceil($totalUsers / $usersPerPage);
     $currentPage = is_numeric($this->get(1)) && $this->get(1) > 0 && $this->get(1) <= $pages ? $this->get(1) : 1;
     $players = array();
     $dbP = R::find('user', ' 1=1 ORDER BY xp DESC LIMIT ?,?', array(($currentPage - 1) * $usersPerPage, $usersPerPage));
     $i = $usersPerPage * ($currentPage - 1) + 1;
     foreach ($dbP as $p) {
         $players[] = array("rank" => $i, "username" => $p->username, "level" => $p->level, "xp" => formatCash($p->xp), "premium" => $p->hasPremium());
         $i++;
     }
     Framework::TPL()->assign('players', $players);
     Framework::TPL()->assign('currentPage', $currentPage);
     Framework::TPL()->assign('pages', $pages);
 }
Esempio n. 26
0
 function new_post($f3)
 {
     $dry = \R::find('images', 'tools_id=?', array($f3->get('POST.tool')));
     // Upload File & Set External Flag
     if (!($this->D->url = $this->upload($f3))) {
         throw new \Exception('No File!');
     }
     $this->D->tools_id = $f3->get('POST.tool');
     $this->D->thumb = $dry ? NULL : 1;
     $id = \R::store($this->D);
     if ($f3->get('dry')) {
         logger($f3, 'added    ' . $this->class_name() . ', id=' . $id);
     } else {
         logger($f3, 'modified ' . $this->class_name() . ', id=' . $id);
     }
     $f3->reroute($this->redirect());
 }
Esempio n. 27
0
 public function _getDbRegistries($table, $parameters)
 {
     $query = '';
     $paramArray = array();
     $counter = 0;
     foreach ($parameters as $key => $value) {
         if ($counter !== 0) {
             $query .= ' AND ' . $key . ' = :' . $key;
         } else {
             $query = $key . ' = :' . $key;
         }
         $paramArray[':' . $key] = $value;
         $counter++;
     }
     $registry = R::find($table, $query, $paramArray);
     return $registry;
 }
Esempio n. 28
0
 /**
  * Handle the viewing of my publications
  *
  * @param object    $context    The context object for the site
  *
  * @return string    A template name
  */
 public function handle($context)
 {
     # Ensure user must be staff.
     $context->mustbestaff();
     # Get the publications the user owns.
     $pubs = R::find('publication', 'uploader_id = ?', array($context->user()->id));
     # Get the URL for the paginator.
     $url = $context->action() . '?';
     # Other paginator info.
     $pagesize = 5;
     $amount = count($pubs);
     $page = $context->getpar('page', 1);
     # Slice the publication array by pagination amount (5 per page)
     $pubs = array_slice($pubs, ($page - 1) * $pagesize, $pagesize);
     # Delegate the publishement bean to the results handler.
     return (new Results($pubs, $url, $pagesize, $amount, $page))->handle($context);
 }
Esempio n. 29
0
 public function chargerInMemory($cod_acervo, $titulo, $tipo_obra, $classificacao, $referencia, $link_capa, $link_dados)
 {
     $this->setCod_acervo($cod_acervo);
     $this->setTitulo($titulo);
     $this->setTipo_obra($tipo_obra);
     $this->setClassificacao($classificacao);
     $this->setReferencia($referencia);
     $this->setLink_dados($link_dados);
     if ($cod_acervo != "") {
         if (R::find("acervocapa", "cod_acervo = " . $this->getCod_acervo())) {
             $this->setLink_capa(true);
         } else {
             $this->setLink_capa(false);
         }
     }
     return $this;
 }
Esempio n. 30
0
 public function execute()
 {
     $this->template->heading('ORM Example');
     // Call ORM plugin.
     $this->factory('orm');
     // Will create a table called 'book';
     $book = R::dispense('example_book');
     // Deleting a record
     if (!empty($_GET['delete'])) {
         $sold = R::load("example_book", $_GET['delete']);
         R::trash($sold);
         $this->template->note(sprintf('Record %s was deleted', $_GET['delete']));
     }
     // Sell a book
     if (!empty($_GET['sell'])) {
         $title = urldecode($_GET['title']);
         $this->template->ok("Great, thanks for buying \"{$title}\". You are a little weird reading this, but who are we to judge.", false, false);
     }
     // To update a field, you need to provide the id (always id) like so;
     // $book->id = 1;
     // Will execute saving to database.
     if (!empty($_GET['sell'])) {
         $sold = $book->import($_GET, 'category,type,author,price,title');
         if ($sold) {
             $this->template->ok("That went well, we just sold another book.", false, false);
         }
         R::store($book);
     }
     // Reading from ORM is just as simple...
     $books = R::find('example_book');
     $book1 = $this->navigation->sefURL(null, 'sell=true&category=books&type=Sci-Fiction&author=Peter Viljoen&price=3.99&title=The Robot Rapist');
     $book2 = $this->navigation->sefURL(null, 'sell=true&category=books&type=Health&author=Samie Caster&price=2.99&title=Getting hard again');
     $book3 = $this->navigation->sefURL(null, 'sell=true&category=books&type=Horror&author=Lion Wessels&price=8.99&title=Cinderella goes rogue');
     // Please see http://redbeanphp.com/ for complete manual.
     // For all R methods see : http://www.redbeanphp.com/api/class_r.html
     $view = $this->factory('views');
     $view->set('delete', $this->navigation->sefURL(null, 'delete='));
     $view->set('special1', $book1);
     $view->set('special2', $book2);
     $view->set('special3', $book3);
     $view->set('books', $books);
     $view->show();
 }