Example #1
0
 public function show_Data()
 {
     $this->output('cash', $this->user->cash);
     $this->output('xp', $this->user->xp);
     $this->output('level', $this->user->level);
     $this->output('players_online', R::getCell('SELECT COUNT(id) FROM session WHERE expires > ?', array(time())));
 }
 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;
             }
         }
     }
 }
 /**
  * Test SQLite table rebuilding.
  * 
  * @return void
  */
 public function testRebuilder()
 {
     $toolbox = R::$toolbox;
     $adapter = $toolbox->getDatabaseAdapter();
     $writer = $toolbox->getWriter();
     $redbean = $toolbox->getRedBean();
     $pdo = $adapter->getDatabase();
     R::dependencies(array('page' => array('book')));
     $book = R::dispense('book');
     $page = R::dispense('page');
     $book->ownPage[] = $page;
     $id = R::store($book);
     $book = R::load('book', $id);
     asrt(count($book->ownPage), 1);
     asrt((int) R::getCell('SELECT COUNT(*) FROM page'), 1);
     R::trash($book);
     asrt((int) R::getCell('SELECT COUNT(*) FROM page'), 0);
     $book = R::dispense('book');
     $page = R::dispense('page');
     $book->ownPage[] = $page;
     $id = R::store($book);
     $book = R::load('book', $id);
     asrt(count($book->ownPage), 1);
     asrt((int) R::getCell('SELECT COUNT(*) FROM page'), 1);
     $book->added = 2;
     R::store($book);
     $book->added = 'added';
     R::store($book);
     R::trash($book);
     asrt((int) R::getCell('SELECT COUNT(*) FROM page'), 0);
 }
Example #4
0
 public static function getUserLeaderboardCount($type)
 {
     $sql = self::makeUserLeaderboardCountSqlQuery($type);
     $count = R::getCell($sql);
     if ($count === null || is_array($count) && count($count) == 0) {
         $count = 0;
     }
     return $count;
 }
 public function init()
 {
     parent::init();
     // only works if you are in casino
     $ct = R::getCell('SELECT map FROM map_position WHERE user_id = ?', array($this->user->getID()));
     if ($ct != "casino") {
         Framework::redir("game/index");
         exit;
     }
 }
    public function player_count()
    {
        return R::getCell('SELECT
			count(poker_player.id)
		FROM
			poker_player, poker_round, poker_player_poker_round
		WHERE
			poker_round.id = ? AND
			poker_player_poker_round.poker_round_id = poker_round.id AND
			poker_player_poker_round.poker_player_id = poker_player.id', array($this->bean->getID()));
    }
    public function init()
    {
        parent::init();
        $id = $_POST["id"];
        // check if npc is valid
        if (!is_numeric($id) || $id <= 0) {
            $this->error('Invalid ' . $this->_type . '-ID');
        }
        $this->npc = R::load($this->_type, $id);
        if ($this->npc->getID() != $id) {
            $this->error($this->_type . ' doesnt exist!');
        }
        // check if npc has right type
        if ($this->npc->type != $this->myType) {
            $this->error("This " . $this->_type . " is not of " . $this->myType);
        }
        // check if user is nearby
        $userPos = R::findOne('map_position', ' user_id = ?', array($this->user->getID()));
        $dist = sqrt(pow($this->npc->x - $userPos->x, 2) + pow($this->npc->y - $userPos->y, 2));
        if ($dist > 3 || $this->npc->map != $userPos->map) {
            $this->error('Du bist zu weit entfehrt!');
        }
        // check if quest availible
        $this->myNPCQuest = R::relatedOne($this->user, 'quests_npc', ' complete_time = 0 AND (startnpc_id = ? OR stopnpc_id = ?)', array($this->npc->getID(), $this->npc->getID()));
        if ($this->myNPCQuest != null) {
            if ($this->myNPCQuest->startnpc_id == $this->npc->getID()) {
                if ($this->myNPCQuest->accepted == 0) {
                    $this->myNPCQuestRole = 'startnpc';
                    $startnpc = $this->npc->name;
                    $stopnpc = R::getCell('SELECT `name` FROM map_npc WHERE id = ?', array($this->myNPCQuest->stopnpc_id));
                }
            } else {
                if ($this->myNPCQuest->accepted == 1) {
                    $this->myNPCQuestRole = 'stopnpc';
                    $stopnpc = $this->npc->name;
                    $startnpc = R::getCell('SELECT `name` FROM map_npc WHERE id = ?', array($this->myNPCQuest->startnpc_id));
                }
            }
            if ($this->myNPCQuestRole != 'none') {
                $all = Config::getConfig('npc_quests');
                $this->myNPCQuestData = $all[$this->myNPCQuest->quest_id][$this->myNPCQuestRole];
                $this->myNPCQuestData["text"] = str_replace(array('{startnpc}', '{stopnpc}'), array($startnpc, $stopnpc), $this->myNPCQuestData["text"]);
                foreach ($this->myNPCQuestData["items"] as $k => $v) {
                    $this->myNPCQuestData["items"][$k]["param"] = str_replace(array('{startnpc}', '{stopnpc}'), array($startnpc, $stopnpc), $v["param"]);
                }
                if ($this->_controllerFunc == 'Interact') {
                    $this->output('quest', '<br /> <br />
					<b>Quest:</b> ' . htmlspecialchars($this->myNPCQuestData["text"]) . ' <br />
					<a href="#questing">' . ($this->myNPCQuestRole == 'startnpc' ? 'annehmen' : 'abschließen') . '</a>');
                }
            }
        }
    }
 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);
 }
Example #9
0
 public static function sendAnswer($uid, $qno, $answer, $optional)
 {
     $id = R::getCell('select id from answer where uid = ? and qno = ? order by id desc limit 1', [$uid, $qno]);
     if (empty($id)) {
         $ans = R::dispense('answer');
         $ans->uid = $uid;
         $ans->datetime = new DateTime();
         $ans->qno = $qno;
         $ans->answer = $answer;
         $ans->optional = $optional;
         return R::store($ans);
     } else {
         $ans = R::load('answer', $id);
         $ans->answer = $answer;
         $ans->optional = $optional;
         return R::store($ans);
     }
 }
 /**
  * Optimize table column types, based on hints
  * @param string  $table   name of the table
  * @param string  $columnName name of the column
  * @param string  $datatype
  */
 public static function optimize($table, $columnName, $datatype, $length = null)
 {
     try {
         $databaseColumnType = DatabaseCompatibilityUtil::mapHintTypeIntoDatabaseColumnType($datatype, $length);
         if (isset(self::$optimizedTableColumns[$table])) {
             $fields = self::$optimizedTableColumns[$table];
             // It is possible that field is created outside optimizer, so in this case reload fields from database
             if (!in_array($columnName, array_keys($fields))) {
                 $fields = R::$writer->getColumns($table);
             }
         } else {
             $fields = R::$writer->getColumns($table);
         }
         if (in_array($columnName, array_keys($fields))) {
             $columnType = $fields[$columnName];
             if (strtolower($columnType) != strtolower($databaseColumnType)) {
                 if (strtolower($datatype) == 'string' && isset($length) && $length > 0) {
                     $maxLength = R::getCell("SELECT MAX(LENGTH({$columnName})) FROM {$table}");
                     if ($maxLength <= $length) {
                         R::exec("alter table {$table} change {$columnName} {$columnName} " . $databaseColumnType);
                     }
                 } else {
                     R::exec("alter table {$table} change {$columnName} {$columnName} " . $databaseColumnType);
                 }
             }
         } else {
             R::exec("alter table {$table} add {$columnName} " . $databaseColumnType);
         }
     } catch (RedBean_Exception_SQL $e) {
         //42S02 - Table does not exist.
         if (!in_array($e->getSQLState(), array('42S02'))) {
             throw $e;
         } else {
             R::$writer->createTable($table);
             R::exec("alter table {$table} add {$columnName} " . $databaseColumnType);
         }
     }
     if (isset($fields)) {
         self::$optimizedTableColumns[$table] = $fields;
     } else {
         self::$optimizedTableColumns[$table] = R::$writer->getColumns($table);
     }
     self::$optimizedTableColumns[$table][$columnName] = $databaseColumnType;
 }
Example #11
0
 public function testSavingNewParentAccountSavesCorrectly()
 {
     $oldMetadata = Account::getMetadata();
     $newMetadata = $oldMetadata;
     $newMetadata['Account']['rules'][] = array('type', 'default', 'value' => 'Customer');
     Account::setMetadata($newMetadata);
     $account = new Account();
     $account->name = 'Account';
     $account->type->value = 'Customer';
     $account->account = $account;
     $saved = $account->save();
     $this->assertTrue($saved);
     $account->account = null;
     $saved = $account->save();
     $this->assertTrue($saved);
     $count = R::getCell('select count(*) from account');
     $this->assertEquals(1, $count);
     Account::setMetadata($oldMetadata);
     $this->assertTrue($account->delete());
 }
Example #12
0
 public function show_Main()
 {
     if ($this->get(1) == "login") {
         Framework::TPL()->assign('first_login', true);
     } else {
         Framework::TPL()->assign('first_login', false);
     }
     $session_expired = false;
     if ($this->get(1) == "session_expired") {
         $session_expired = true;
     }
     Framework::TPL()->assign('session_expired', $session_expired);
     $count = R::getCell('select count(id) from user');
     Framework::TPL()->assign("playercount", $count);
     // assign news
     $news = array();
     $dbNews = R::find('homepage_posts', ' 1=1 ORDER BY id DESC LIMIT 3');
     foreach ($dbNews as $n) {
         $author = R::relatedOne($n, 'user');
         $news[] = array('id' => $n->id, 'title' => $n->title, 'author' => $author->username, 'time' => $n->time);
     }
     Framework::TPL()->assign("news", $news);
 }
    ?>
		    <div class="uiv2-form-row">
		    	<span class="uiv2-form-label">Registered on</span>
		        <span class="uiv2-form-label" style="text-align: left; ">
		        	<?php 
    echo date('d-m-Y', strtotime($user["date_of_registration"]));
    ?>
</span>
		    </div>
		    		<?php 
}
?>
		</fieldset>
		<?php 
$sql = "select count(*) from userservices where userid=?";
$services_count = R::getCell($sql, array($id));
if ($services_count > 0) {
    ?>
		<h2>Services offered</h2>

		<?php 
    $sql = "select distinct c.id as id, category from categories c " . "join services s on c.id = s.category_id " . "join userservices us on s.id = us.serviceid " . "where userid=?";
    $categories = R::getAll($sql, array($id));
    foreach ($categories as $category) {
        ?>
		<fieldset>
			<div class="legend"><?php 
        echo $category["category"];
        ?>
</div>
			<div style="padding: 20px;">
    header('Content-type:text/json;charset=utf-8');
    echo json_encode(['result' => 'failed', 'error' => 'db error kayako', 'details' => $e->getMessage()]);
    die;
}
R::close();
// Save frequent people
R::addDatabase('supportsr', $GLOBALS['db_supportsr_url'], $GLOBALS['db_supportsr_user'], $GLOBALS['db_supportsr_pass']);
R::selectDatabase('supportsr');
if (!R::testConnection()) {
    exit('DB failed' . PHP_EOL);
}
R::freeze(true);
try {
    R::begin();
    foreach ($people_array as $people) {
        $person_old = R::getCell(' SELECT id ' . '   FROM supportsr.esr_frequent_people ' . '  WHERE name = :name ' . '    AND paper_number = :p_number ', [':name' => $people->pname, ':p_number' => $people->pidval]);
        if (empty($person_old) || $person_old == "") {
            $person_new = R::getRedBean()->dispense('esr_frequent_people');
            $person_new->name = $people->pname;
            $person_new->paper_type = $people->ptype == '身份证' ? '身份证/Id card' : ($people->ptype == '台胞证' ? '台胞证/Efficiency certificate' : ($people->ptype == '护照' ? '护照/Passport' : ($people->ptype == '港澳通行证' ? '港澳通行证/Hong Kong-Macau passport' : ($people->ptype == '驾驶证' ? '驾驶证/Driving license' : ''))));
            $person_new->paper_number = $people->pidval;
            $person_new->comid = $user['organizationname'] . '|*|' . $user['userorganizationid'];
            $person_new_id = R::store($person_new);
        }
    }
    R::commit();
} catch (Exception $e) {
    header('Content-type:text/json;charset=utf-8');
    echo json_encode(['result' => 'failed', 'error' => 'db error kayako', 'details' => $e->getMessage()]);
    R::rollback();
    die;
Example #15
0
}
if (empty($staff_rate_score) || $staff_rate_score == NULL) {
    $staff_rate_score = 4.0;
}
if (!empty($staff_id) && is_numeric($staff_id)) {
    try {
        $staff_experience_count = R::getCell(' SELECT ' . '     COUNT(DISTINCT p.ticketid) ' . ' FROM ' . '     kayako_fusion.swticketposts p ' . ' WHERE ' . '     p.staffid = :staff_id ', [':staff_id' => $staff_id]);
        _log(json_encode(['staff_experience_count' => $staff_experience_count]));
    } catch (Exception $e) {
        header('Content-type:text/json;charset=utf-8');
        echo json_encode(['result' => 'failed', 'error' => 'db error portal', 'details' => $e->getMessage()]);
        die;
    }
} else {
    try {
        $staff_experience_count = R::getCell('     SELECT COUNT(*) AS experience_count' . '       FROM supportsr.esr_ticketworkorder_interface p' . ' INNER JOIN supportsr.esr_ticketworkorder_interface pp' . '         ON p.wo_assignee = pp.wo_assignee' . '        AND p.wo_category = pp.wo_category' . '      WHERE p.kayako_ticket_id = :ticket_id', [':ticket_id' => $ticket_id]);
        _log(json_encode(['staff_experience_count' => $staff_experience_count]));
    } catch (Exception $e) {
        header('Content-type:text/json;charset=utf-8');
        echo json_encode(['result' => 'failed', 'error' => 'db error portal', 'details' => $e->getMessage()]);
        die;
    }
}
R::close();
// Merge
$staff_skills['rate_score'] = $staff_rate_score;
$staff_skills['experience_count'] = $staff_experience_count;
// Return
header('Content-type:text/json;charset=utf-8');
echo json_encode(['result' => 'true', 'staff' => $staff_skills], JSON_UNESCAPED_UNICODE);
die;
Example #16
0
require 'api_rb.php';
require 'api_db.php';
$start_date = isset($_REQUEST['start']) ? $_REQUEST['start'] : date('Y-m-d', time() - 7 * 24 * 60 * 60);
$end_date = isset($_REQUEST['end']) ? $_REQUEST['end'] : date('Y-m-d');
// Log
_log(json_encode(['start_date' => $start_date, 'end_date' => $end_date]));
// Wechat
R::addDatabase('wechat_csc', $GLOBALS['db_wechat_csc_url'], $GLOBALS['db_wechat_csc_user'], $GLOBALS['db_wechat_csc_pass']);
R::selectDatabase('wechat_csc');
if (!R::testConnection()) {
    exit('DB failed' . PHP_EOL);
}
R::freeze(true);
// Get all
try {
    $users_count = R::getCell('SELECT COUNT(0) ' . '  FROM wechat_csc.wxcsc_focus ' . ' WHERE (openid, opt_ts) IN ' . '       (  SELECT openid, MAX(opt_ts) ts ' . '            FROM wechat_csc.wxcsc_focus ' . '        GROUP BY openid) ' . '    AND OPERATION = "focus" ');
} catch (Exception $e) {
    header('Content-type:text/json;charset=utf-8');
    echo json_encode(['result' => 'failed', 'error' => 'db error wechat', 'details' => $e->getMessage()]);
    die;
}
// Get in raqnge
try {
    $users_focus = R::getAll('   SELECT openid, operation, MAX(opt_ts) AS focus_at ' . '     FROM wechat_csc.wxcsc_focus ' . '    WHERE opt_ts BETWEEN STR_TO_DATE(:start_date, "%Y-%m-%d") AND STR_TO_DATE(:end_date, "%Y-%m-%d") ' . ' GROUP BY openid, operation ', [':start_date' => $start_date, ':end_date' => $end_date]);
} catch (Exception $e) {
    header('Content-type:text/json;charset=utf-8');
    echo json_encode(['result' => 'failed', 'error' => 'db error wechat', 'details' => $e->getMessage()]);
    die;
}
R::close();
// Check
Example #17
0
 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");
 }
Example #18
0
 /**
  * See the yii documentation. This function is made public for unit testing.
  * @return int|string
  */
 public function calculateTotalItemCount()
 {
     $selectQueryAdapter = new RedBeanModelSelectQueryAdapter();
     $sql = $this->makeSqlQueryForFetchingTotalItemCount($selectQueryAdapter, true);
     $count = R::getCell($sql);
     if ($count === null || empty($count)) {
         $count = 0;
     }
     return $count;
 }
Example #19
0
 /**
  * Get the row count in a given table.
  * @param string $tableName
  * @return integer
  */
 public static function getCount($tableName, $where = null)
 {
     $sql = 'select count(*) count from ' . $tableName;
     if ($where != null) {
         $sql .= ' where ' . $where;
     }
     $count = R::getCell($sql);
     if ($count === null) {
         $count = 0;
     }
     return $count;
 }
Example #20
0
 protected static function fastContainsUserByGroupId($groupId, $userId)
 {
     assert('is_int($groupId) && $groupId > 0');
     // Not Coding Standard
     assert('is_int($userId)  && $userId  > 0');
     // Not Coding Standard
     return R::getCell("select group_contains_user({$groupId}, {$userId});") == 1;
 }
Example #21
0
 public function chat_post()
 {
     $app = $this->app;
     $db = $app->db;
     $get = $app->get;
     if (!$app->session['admin']->can('chat', 'post')) {
         throw new \exception('You are not allowed to create masterlist items (Permission Denied)');
     }
     $msg = isset($get['msg']) ? $get['msg'] : false;
     if (!empty($msg)) {
         $filter = $app->filter;
         $t = $db->model('chat');
         $t->admin_id = $app->session['admin']->id;
         $t->timestamp = time();
         $t->message = $filter->min($msg);
         $id = $db->store($t);
     }
     $matches = [];
     $has_match = preg_match('/\\@(\\w+)\\:/', $t->message, $matches);
     if ($has_match == 1 || count($matches) > 0) {
         //we have a mention in the chat
         foreach ($matches as $name) {
             if (!is_null($name) && !empty($name) && $name !== $app->session['admin']->name) {
                 $admin_id = \R::getCell('SELECT id FROM admin WHERE name=:name', [':name' => $name]);
                 if (!empty($admin_id)) {
                     $t = $db->model('notification');
                     $t->admin_id = $admin_id;
                     $t->message = $app->session['admin']->name . ' mentioned you in chat.';
                     $t->url = 'javascript:openChatClearNote(this)';
                     $t->timestamp = time();
                     $t->icon = 'fa-comment';
                     $t->type = 'warning';
                     $db->store($t);
                 }
             }
         }
     }
     return ['error' => 0, 'message' => $id];
 }
Example #22
0
 /**
  * @param $modelClassName
  * @param $joinTablesAdapter null or instance of joinTablesAdapter.
  * @param $modelClassName Pass only when getting it at runtime gets the wrong name.
  */
 public static function getCount(RedBeanModelJoinTablesQueryAdapter $joinTablesAdapter = null, $where = null, $modelClassName = null, $selectDistinct = false)
 {
     assert('$where          === null || is_string($where)');
     assert('$modelClassName === null || is_string($modelClassName) && $modelClassName != ""');
     if ($modelClassName === null) {
         $modelClassName = get_called_class();
     }
     if ($joinTablesAdapter == null) {
         $joinTablesAdapter = new RedBeanModelJoinTablesQueryAdapter($modelClassName);
     }
     $tableName = self::getTableName($modelClassName);
     $sql = static::makeSubsetOrCountSqlQuery($tableName, $joinTablesAdapter, null, null, $where, null, true, $selectDistinct);
     $count = R::getCell($sql);
     if ($count === null || empty($count)) {
         $count = 0;
     }
     return intval($count);
 }
Example #23
0
 // check for numerics in phone
 // check for email pattern
 // check for existence of phone
 // check for existence of email
 // check for existence of username
 if ($is_valid) {
     unset($_POST["confirm_password"]);
     unset($_POST["human_check"]);
     $services = $_POST["service"];
     unset($_POST["service"]);
     $new_user = R::dispense("users");
     $new_user->import($_POST);
     $new_user->date_of_registration = date('Y-m-d h:i:s');
     $new_user->password = md5($new_user->password);
     $new_user->profile_picture = $attachment;
     $approval_required = R::getCell("select approval_required from usertypes where id =?", array($new_user->usertype));
     if ($approval_required == 1) {
         $new_user->registration_status = "pending";
     } else {
         $new_user->registration_status = "approved";
     }
     store_in_session("approval_required", $approval_required);
     // print_r($new_user);
     R::store($new_user);
     // echo "-------------------------\n";
     if (!empty($services)) {
         foreach ($services as $service) {
             $userservice = R::dispense("userservices");
             $userservice->userid = $new_user->id;
             $userservice->serviceid = $service;
             // echo "===========================\n";
    private function foundCompany()
    {
        if (!$this->company) {
            $myBalance = R::getCell('SELECT balance FROM bank_account WHERE user_id = ?', array($this->user->id));
            if (isset($_POST['foundName']) && isset($_POST["foundCash"]) && is_numeric($_POST["foundCash"])) {
                $fName = $_POST['foundName'];
                $fCash = $_POST['foundCash'];
                if ($fCash < 0 || $fCash > $myBalance) {
                    $this->output('maintext', 'Du hast ein ungültiges Startkapital angegeben.');
                    $this->output('options', array('interact' => 'Zurück'));
                    return true;
                }
                $isUnique = R::getCell('SELECT COUNT(id) FROM company WHERE LOWER(name) = LOWER(?)', array($fName));
                if ($isUnique != 0) {
                    $this->output('maintext', 'Der angegebene Name wird bereits verwendet.');
                    $this->output('options', array('interact' => 'Zurück'));
                    return true;
                }
                $company = R::dispense('company');
                $company->name = $fName;
                $company->user = $this->user;
                $company->balance = $fCash;
                $company->lastCalc = time();
                R::$adapter->startTransaction();
                try {
                    R::store($company);
                } catch (Exception $e) {
                    R::$adapter->rollback();
                    $this->output('maintext', $e->getMessage());
                    $this->output('options', array('interact' => 'Zurück'));
                    return true;
                }
                R::exec('UPDATE bank_account SET balance = balance - ? WHERE user_id = ?', array($fCash, $this->user->id));
                R::$adapter->commit();
                $this->output('maintext', 'Herzlichen Glückwunsch! Die Firma ' . htmlspecialchars($company->name) . ' wurde
				soeben gegründet.');
                $this->output('options', array('interact' => 'Weiter'));
                return true;
            }
            $this->output('maintext', 'Willkommen im BusinessManager-System. Von hier kannst
			du deine Firma und ihre Fabrikation verwalten. <br /> <br />
			Du besitzt derzeit noch keine Firma. Um eine Firma zu gründen brauchen wir
			einen Namen, und wie viel Startkapital von deinem Konto auf das Firmenkonto
			überwiesen werden soll.<br />
			Dein derzeitiger Kontostand beträgt ' . formatCash($myBalance) . ' {money}. <br /> <br />
			<i>Hinweis: Der Name kann nachträglich nicht mehr geändert werden!</i>');
            $this->output('form', array('target' => 'interact', 'elements' => array(array('desc' => 'Name der Firma', 'type' => 'text', 'name' => 'foundName'), array('desc' => 'Startkapital', 'type' => 'text', 'name' => 'foundCash'))));
            return true;
        }
        return false;
    }
Example #25
0
 public static function getNextLayoutId()
 {
     return max(2, (int) R::getCell('select max(layoutId) + 1 from dashboard'));
 }
Example #26
0
 /**
  * Stored and reloads spatial data to see if the
  * value is preserved correctly.
  */
 protected function setGetSpatial($data)
 {
     R::nuke();
     $place = R::dispense('place');
     $place->location = $data;
     //R::$f->GeomFromText('"'.$data.'"');
     R::store($place);
     asrt(R::getCell('SELECT AsText(location) FROM place LIMIT 1'), $data);
 }
 public function testPermissionsCachingBasics()
 {
     if (!SECURITY_OPTIMIZED) {
         return;
     }
     $accounts = Account::getAll();
     $account = $accounts[0];
     $user = User::getByUsername('bobby');
     $this->assertNotEquals($account->owner->id, $user->id);
     $account->addPermissions($user, Permission::READ);
     $this->assertTrue($account->save());
     $securableItemId = $account->getClassId('SecurableItem');
     $permitableId = $user->getClassId('Permitable');
     R::exec("call get_securableitem_cached_actual_permissions_for_permitable({$securableItemId}, {$permitableId}, @allow_permissions, @deny_permissions)");
     $allow_permissions = intval(R::getCell('select @allow_permissions'));
     $deny_permissions = intval(R::getCell('select @deny_permissions'));
     $this->assertEquals(Permission::NONE, $allow_permissions);
     $this->assertEquals(Permission::NONE, $deny_permissions);
     ZurmoDatabaseCompatibilityUtil::callProcedureWithoutOuts("cache_securableitem_actual_permissions_for_permitable({$securableItemId}, {$permitableId}, 1, 0)");
     R::exec("call get_securableitem_cached_actual_permissions_for_permitable({$securableItemId}, {$permitableId}, @allow_permissions, @deny_permissions)");
     $allow_permissions = intval(R::getCell('select @allow_permissions'));
     $deny_permissions = intval(R::getCell('select @deny_permissions'));
     $this->assertEquals(Permission::READ, $allow_permissions);
     $this->assertEquals(Permission::NONE, $deny_permissions);
     ZurmoDatabaseCompatibilityUtil::callProcedureWithoutOuts("clear_cache_securableitem_actual_permissions({$securableItemId})");
     R::exec("call get_securableitem_cached_actual_permissions_for_permitable({$securableItemId}, {$permitableId}, @allow_permissions, @deny_permissions)");
     $allow_permissions = intval(R::getCell('select @allow_permissions'));
     $deny_permissions = intval(R::getCell('select @deny_permissions'));
     $this->assertEquals(Permission::NONE, $allow_permissions);
     $this->assertEquals(Permission::NONE, $deny_permissions);
     $account->removeAllPermissions();
     $this->assertTrue($account->save());
     $this->assertEquals(Permission::NONE, $account->getEffectivePermissions($user));
     $this->assertEquals(array(Permission::NONE, Permission::NONE), $account->getExplicitActualPermissions($user));
     $this->assertEquals(array(Permission::NONE, Permission::NONE), $account->getInheritedActualPermissions($user));
 }
Example #28
0
 public function updateRecord($table, $updateValues, $id = NULL)
 {
     $flagNeedsReturnID = !$id;
     if ($flagNeedsReturnID) {
         R::exec('SET @uuid = uuid() ');
     }
     $id = parent::updateRecord($table, $updateValues, $id);
     if ($flagNeedsReturnID) {
         $id = R::getCell('SELECT @uuid');
     }
     return $id;
 }
Example #29
0
if ($openid == '') {
    header('Location: ' . $csc_url_base . '/static/html/user_not_focus_csc.html?bcb=' . $callback . '&rand=' . rand() . '#mp.weixin.qq.com');
    die;
}
if (!isset($_SESSION['openid'])) {
    $_SESSION['openid'] = $openid;
}
// Query
R::addDatabase('wechat_csc', $GLOBALS['db_wechat_csc_url'], $GLOBALS['db_wechat_csc_user'], $GLOBALS['db_wechat_csc_pass']);
R::selectDatabase('wechat_csc');
if (!R::testConnection()) {
    exit('DB failed' . PHP_EOL);
}
R::freeze(true);
try {
    $user_email = R::getCell('SELECT wu.email' . '  FROM wxcsc_users wu' . ' WHERE wu.openid = :openid' . ' LIMIT 1', [':openid' => $openid]);
} catch (Exception $e) {
    header('Location: ' . $csc_url_base . '/static/html/error_message.html?msg=' . urlencode($e->getMesage()) . '&rand=' . rand() . '#mp.weixin.qq.com');
    die;
}
R::close();
_log(json_encode(['openid' => $openid, 'user_email' => $user_email]));
// Error return
if ($user_email == '') {
    if ($callback == 'user_bind_check_csc') {
        header('Location: ' . $csc_url_base . '/static/html/user_bind_1_csc.html?rand=' . rand() . '#mp.weixin.qq.com');
        die;
    } else {
        if (in_array($callback, ['extra_news', 'extra_expert', 'dc_guide', 'extra_contact'])) {
            header('Location: ' . $csc_url_base . '/static/html/' . $callback . '.html?rand=' . rand() . '#mp.weixin.qq.com');
            die;
Example #30
0
    $id = $_REQUEST["id"];
}
include_once "config.php";
$current_user = get_from_session("current_user");
if (is_null($current_user)) {
    ?>
		<div>
			<h3>Please login to access this feature</h3>
		</div>

		<?php 
    return;
}
$sql = "select * from users where id = ?";
$user = R::getRow($sql, array($id));
$usertype = R::getCell("select typename from usertypes where id = ?", array($user["usertype"]));
?>


<div>
	<form class="classic">
	<div style="width: 150px; padding: 10px; float: left; min-height: 500px; ">
		<p>
			<?php 
$profile_picture = "images/profile/default.jpg";
if ($user["profile_picture"] != null) {
    $profile_picture = $user["profile_picture"];
}
?>
			<img src="<?php 
echo $profile_picture;