Exemple #1
0
 /**
  * Vote
  * POST
  *
  * @param Request $request
  * @param RPG $rpgLib
  * @return Response
  */
 public function vote(Request $request, RPG $rpgLib)
 {
     $user = UserManager::find(Auth::user()->guid);
     $time = time();
     $this->validate($request, ['out' => 'required|numeric']);
     if ($request->out != $rpgLib->getValueOut()) {
         return redirect()->back();
     } elseif (($time - $user->heurevote) / 60 < 180) {
         return redirect()->back();
     }
     $user->points += config('config.points.vote');
     $user->votes += 1;
     $user->heurevote = $time;
     $user->save();
     return redirect()->route('home');
 }
Exemple #2
0
 /**
  * Returns an instance of an RPG_Auth subclass, given the username,
  * password, and an adapter class name. If the adapter is not given,
  * it will use the authAdapter setting as defined in config.php.
  *
  * @param  string $username
  * @param  string $password
  * @param  string $adapter
  * @return RPG_Auth subclass
  */
 public static function factory($username, $password, $adapter = null)
 {
     if ($adapter === null) {
         $adapter = RPG::config('authAdapter');
     }
     if (is_string($adapter) and class_exists($adapter) and is_subclass_of($adapter, 'RPG_Auth')) {
         return new $adapter($username, $password);
     }
 }
Exemple #3
0
    /**
     * Creates a new user record on the local database, if it doesn't exist.
     *
     * @param  array $user
     */
    protected function _createLocalRecord(array $user)
    {
        $db = RPG::database();
        $existing = $db->query('SELECT user_id FROM {user}
								WHERE user_external_id = :0', $user['userid']);
        if ($existing->getNumRows() > 0) {
            $userId = $existing->fetchOne();
        } else {
            /* TODO: this should replace the raw insert()
            			
            			$obj = RPG::model('user')->getObject();
            			$obj->user_name = htmlspecialchars_decode($user['username'], ENT_COMPAT);
            			$obj->user_email = $user['email'];
            			$obj->user_external_id = $user['userid'];
            			RPG::model('user')->insert($obj);
            			*/
            $userId = $db->insert('user', array('user_name' => htmlspecialchars_decode($user['username'], ENT_COMPAT), 'user_password' => '', 'user_salt' => RPG::model('user')->generateSalt(5), 'user_email' => $user['email'], 'user_autologin' => '', 'user_autologin_time' => 0, 'user_money' => 0, 'user_external_id' => $user['userid'], 'user_joindate' => RPG_NOW));
        }
        return $userId;
    }
Exemple #4
0
 /**
  * Fetches a set of entries, given a series of options.
  *
  * - getBody: Will fetch the body of each entry (true)
  * - getUser: Will fetch the author name (true)
  * - limit:   Max number of entries to fetch (5)
  * - offset:  Number to start fetching entries (0)
  * - where:   Optional where clause (array())
  * - order:   How to order the result (array('news_time' => 'DESC'))
  *
  * @param  array $options List of options.
  * @return array News entries referenced by news_id.
  */
 public function getEntries(array $options = array())
 {
     $default = array('getBody' => true, 'getUser' => true, 'limit' => 5, 'offset' => 0, 'where' => array(), 'order' => array('news_time' => 'DESC'));
     $options = array_merge($default, $options);
     $select = RPG::database()->select('news')->addColumns('news_id', 'news_author', 'news_title', 'news_time');
     if ($options['getBody']) {
         $select->addColumns('news_body');
     }
     if ($options['getUser']) {
         $select->addColumns('user_name')->addLeftJoin('user', 'user_id = news_author');
     }
     if ($options['where']) {
         // first element is condition, and the rest are bind params
         $where = array_shift($options['where']);
         $select->addWhere($where);
         $select->setBind($options['where']);
     }
     $select->setOrderBy($options['order'])->setLimit($options['limit'], $options['offset']);
     return $select->execute()->fetchMapped('news_id');
 }
Exemple #5
0
 /**
  * Validates the form token given in a request.
  *
  * @param  string $formKey Unique form key.
  * @return bool
  * @throws RPG_Exception_Token in case of error.
  */
 public function checkFormToken($formKey)
 {
     // pick the token from the request
     $userToken = RPG::input()->post('csrf_token', 'string');
     // token wasn't there?
     if (empty($userToken)) {
         throw new RPG_Exception_Token(RPG_Exception_Token::MISSING);
     }
     // token wasn't set server-side?
     if (!isset($_SESSION['_csrf'][$formKey])) {
         throw new RPG_Exception_Token(RPG_Exception_Token::INVALID);
     }
     list($time, $token) = explode('|', $_SESSION['_csrf'][$formKey]);
     // token expired?
     if (intval($time) < RPG_NOW - self::FORM_TOKEN_MAX_AGE) {
         throw new RPG_Exception_Token(RPG_Exception_Token::EXPIRED);
     }
     // check to make sure tokens match
     if ($userToken !== $token) {
         throw new RPG_Exception_Token(RPG_Exception_Token::INVALID);
     }
     // remove existing token and return success.
     unset($_SESSION['_csrf'][$formKey]);
     return true;
 }
Exemple #6
0
 /**
  * Outputs the page to the browser.
  * 
  * @todo In the future, have multiple output formats? XML, JSON, etc.
  */
 public function render()
 {
     // set the styles/css/javascript, and render to $output
     $output = $this->getLayout()->set(array('styleSheets' => $this->_styleSheets, 'inlineCss' => $this->_inlineCss, 'scriptFiles' => $this->_scriptFiles, 'inlineScript' => $this->_inlineScript, 'navigation' => $this->_navigation, 'subNavigation' => $this->_subNavigation, 'navbits' => $this->_navbits))->render();
     $gzworked = false;
     // gzip the output if we can.
     // headers can't be sent or else we won't be able to set content-encoding.
     // only gzipping if output is >1kb, make this configurable?
     if (RPG::config('usegzip') and !RPG::isRegistered('nogzip') and isset($_SERVER['HTTP_ACCEPT_ENCODING']) and strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') !== false and !headers_sent() and strlen($output) > 1024) {
         $output = $this->getGzippedText($output, $gzworked);
     }
     if (!headers_sent()) {
         // send encoding headers if gzip worked
         if ($gzworked) {
             header('Content-Encoding: gzip');
             header('Vary: Accept-Encoding', false);
         }
         header('Content-Length: ' . strlen($output));
         header('Cache-Control: private');
         header('Pragma: private');
     }
     echo $output;
 }
Exemple #7
0
?>
">Admin CP</a>
			<a href="<?php 
echo $this->url('home');
?>
">Home</a>
			<a href="#top">Top</a>
		</div>
		Crindigan Version <?php 
echo RPG_VERSION;
?>
, Copyright &copy; 2009-2010 Steven Harris
	</div>
	
	<?php 
if (RPG::config('debug') and !empty(RPG::$debugMessages)) {
    ?>
	<br />
	<div class="block">
		<div class="block-header">Debugging Output</div>
		<div class="block-body">
			<ul>
			<?php 
    foreach (RPG::$debugMessages as $__debug_msg) {
        echo '<li>', nl2br($__debug_msg), "</li>\n";
    }
    ?>
			<li><a href="<?php 
    echo $this->url('*/debug-list-actions');
    ?>
">View Controller Actions</a></li>
Exemple #8
0
 /**
  * Returns the path info for the request.
  *
  * @param  bool $includeQuery If true, does not remove the query string
  * @param  bool $includeBase If true, does not remove the base path
  * @return string
  */
 public function getPath($includeQuery = false, $includeBase = false)
 {
     // First we'll need a request URI
     $path = $_SERVER['REQUEST_URI'];
     if (isset($_SERVER['HTTP_HOST']) and strpos($path, $_SERVER['HTTP_HOST']) !== false) {
         $path = preg_replace('#^[^:]*://[^/]*/#', '/', $path);
     }
     // Remove the query string if it's present
     if (!$includeQuery and ($query = strpos($path, '?')) !== false) {
         $path = substr($path, 0, $query);
     }
     // Remove the base URL
     $baseUrl = RPG::config('baseUrl');
     if (!$includeBase and !empty($baseUrl)) {
         $baseUrl = rtrim($baseUrl, '/');
         $path = substr($path, strlen($baseUrl));
     }
     $this->_path = $path;
     return $path;
 }
Exemple #9
0
 public function doDelete($key)
 {
     $db = RPG::database();
     $db->delete('hello', array('hello_key = :0', $key));
 }
Exemple #10
0
//
try {
    // Initialize the system
    RPG::setConfig($config);
    RPG_Template::setPath($config['viewPath']);
    RPG_Model::setPath($config['modelPath']);
    RPG::session();
    RPG::user(RPG::model('user'));
    // add this now, so controllers can include CSS that overrides defaults
    RPG::view()->addStyleSheet('media/styles/light.css');
    // Process the request
    RPG::router($config['controllerPath'])->processRequest();
    // stop the timer - needs to be here so it can get rendered via templates
    RPG::debug('Execution Time (pre-render): ' . round(microtime(true) - RPG::get('__debug_time'), 4));
    // Render the output - TODO: handle styles differently later
    RPG::view()->render();
} catch (RPG_Exception $ex) {
    // Basic error page
    echo '<html>
<head>
	<title>Application Error</title>
	<style type="text/css">
	body { font-family: sans-serif; }
	</style>
</head>
<body>
	<h1>Application Error</h1>', "\n";
    if (isset($config['debug']) and $config['debug'] === true) {
        echo $ex;
    } else {
        echo "There has been an internal error within Crindigan.\n";
Exemple #11
0
 /**
  * Exchange money with an external system.
  */
 public function doMoney()
 {
     RPG::view()->setNavCurrent('user', 'user/money')->setTitle('Exchange Money');
 }
Exemple #12
0
 /**
  * Returns the path to the temporary file for the given session ID, using
  * the session path configured in the config file as a base.
  *
  * @param  string $sessionId
  * @return string Path to temporary file: {$sessionPath}/sess_{$sessionId}
  */
 protected function _getFile($sessionId)
 {
     return RPG::config('sessionPath') . '/sess_' . $sessionId;
 }
Exemple #13
0
 public function updateAutoLogin($userId, $key = '', $time = 0)
 {
     $affected = RPG::database()->update('user', array('user_autologin' => $key, 'user_autologin_time' => $time), array('user_id = :0', $userId));
 }
Exemple #14
0
 /**
  * Displays the source code of the given action name.
  *
  * @param  string $actionName  Name of the controller's action method.
  */
 public function doDebugViewAction($actionName)
 {
     if (RPG::config('debug') === true and strpos($actionName, 'do') === 0) {
         $method = new ReflectionMethod($this, $actionName);
         $out = '<h2>' . $method->getDeclaringClass()->getName() . "::{$actionName}()</h2>\n" . '<a href="' . RPG::url('*/debug-list-actions') . '">&laquo; Action List</a><br /><br />';
         $start = $method->getStartLine() - 1;
         $end = $method->getEndLine();
         $file = file($method->getFileName());
         $lines = array_slice($file, $start, $end - $start);
         $out .= "<pre>\n    " . str_replace("\t", '    ', $method->getDocComment()) . "\n";
         foreach ($lines as $line) {
             $out .= htmlentities(str_replace("\t", '    ', $line));
         }
         $out .= '</pre>';
         RPG::view()->setLayout('layouts/empty.php')->setContent($out);
     }
 }
Exemple #15
0
 /**
  * Adds query information to the debug area of the output.
  *
  * @param  string $sql The query text.
  * @param  int $time   The time taken to run the query.
  */
 protected function _writeDebug($sql, $time)
 {
     RPG::debug("<strong>Query #{$this->_queryCount} - {$time}s:</strong> <a href=\"#\" onclick=\"RPG.toggle(this); RPG.toggle('#rpg_debug_query_{$this->_queryCount}'); return false;\">[Show Query]</a><div style=\"display:none\" id=\"rpg_debug_query_{$this->_queryCount}\">{$sql}</div>");
 }
Exemple #16
0
 public function doIndex()
 {
     // just go to HomeController
     RPG::view()->redirect('home');
 }
Exemple #17
0
 /**
  * Returns an escaped internal URL given the path as
  * "controller/action/param1/.../paramN" and an array of elements to
  * include in the query string.
  *
  * @param  string $path
  * @param  array  $query
  * @return string Escaped URL.
  * @see    RPG::url()
  */
 public function url($path, array $query = array())
 {
     return $this->escape(RPG::url($path, $query), true);
 }
Exemple #18
0
 /**
  * Displays more news articles and a navigable archive.
  */
 public function doNews()
 {
     RPG::view()->setNavCurrent('home', 'home/news')->setTitle('News');
 }
Exemple #19
0
 /**
  * Creates the SQL and executes the query.
  *
  * @return RPG_Database_Result
  */
 public function execute()
 {
     return RPG::database()->query($this->getSql(), $this->_bind);
 }
Exemple #20
0
 /**
  * Generates a new autologin key, saves it to the database, and updates
  * the user's cookie.
  */
 public function refreshAutoLogin()
 {
     $loginKey = sha1($this->_model->generateSalt(20));
     $this->_model->updateAutoLogin($this->id, $loginKey, RPG_NOW);
     // set httponly cookie for 30 days
     $this->_input->setCookie('autologin', sha1($loginKey . RPG::config('cookieSalt')), 86400 * 30, true);
     $this->_input->setCookie('userid', $this->id, 86400 * 30, true);
 }
Exemple #21
0
 /**
  * Fetches an instance of the router library, initializing if necessary.
  *
  * @param  string $controllerPath Path where controllers are located.
  * @return RPG_Router
  */
 public static function router($controllerPath = '')
 {
     if (self::$_router === null) {
         if (empty($controllerPath)) {
             throw new RPG_Exception('Controller path cannot be empty on first call to RPG::router()');
         }
         self::$_router = RPG_Router::getInstance();
         self::$_router->setControllerPath($controllerPath);
     }
     return self::$_router;
 }
Exemple #22
0
 /**
  * Logs the user out of the system.
  * 
  * GET Parameters
  * - hash: string
  * - returnto: string
  */
 public function doLogout()
 {
     $user = RPG::user();
     $hash = RPG::input()->get('hash', 'string');
     if ($hash === sha1($user->id . sha1($user->salt) . sha1($user->name) . sha1(RPG::config('cookieSalt')))) {
         $user->clearAutoLogin();
         RPG::session()->regenerateId();
         RPG::session()->loggedIn = false;
         RPG::session()->userId = 0;
         $user->setupGuest();
         RPG::session()->setFlash('frontend_message', 'Logged out successfully.');
     } else {
         RPG::session()->setFlash('frontend_error', 'Invalid logout hash.');
     }
     $returnTo = urldecode(RPG::input()->get('returnto', 'string'));
     $query = array();
     if (strpos($returnTo, '?') !== false) {
         list($path, $queryString) = explode('?', $returnTo);
         parse_str($queryString, $query);
     } else {
         $path = $returnTo;
     }
     RPG::view()->redirect($path, $query);
 }
Exemple #23
0
 /**
  * Processes the current request, handing it off to the proper
  * controller and action.
  */
 public function processRequest()
 {
     $path = RPG::input()->getPath();
     $parts = $this->getUrlParts($path);
     $controller = $this->_getController($parts['controller']);
     $action = $this->_getActionName($parts['action']);
     $this->_parameters = $parts['params'];
     if (!method_exists($controller, $action)) {
         array_unshift($parts['params'], $this->_action);
         $action = 'do404';
         $this->_action = '404';
         //throw new RPG_Exception('Action "' . $action . '" does not exist.');
     }
     call_user_func_array(array($controller, $action), $parts['params']);
 }