User object, new reader role for users

This commit is contained in:
Diego Najar 2018-07-25 23:42:00 +02:00
parent 33c89e8bd7
commit 910545dae2
23 changed files with 394 additions and 249 deletions

1
.gitignore vendored
View File

@ -1,4 +1,5 @@
.DS_Store
dbgenerator.php
bl-content/*
bl-plugins/timemachine
bl-plugins/timemachine-x

View File

@ -1,14 +1,14 @@
<?php defined('BLUDIT') or die('Bludit CMS.');
class dbJSON
{
class dbJSON {
public $db;
public $dbBackup;
public $file;
public $firstLine;
// $file, the JSON file.
// $firstLine, TRUE if you want to remove the first line, FALSE otherwise.
// $firstLine, TRUE if you want to remove the first line, FALSE otherwise
function __construct($file, $firstLine=true)
{
$this->file = $file;
@ -16,26 +16,25 @@ class dbJSON
$this->dbBackup = array();
$this->firstLine = $firstLine;
if(file_exists($file))
{
// Read JSON file.
if (file_exists($file)) {
// Read JSON file
$lines = file($file);
// Remove the first line, the first line is for security reasons.
if($firstLine) {
// Remove the first line, the first line is for security reasons
if ($firstLine) {
unset($lines[0]);
}
// Regenerate the JSON file.
// Regenerate the JSON file
$implode = implode($lines);
// Unserialize, JSON to Array.
// Unserialize, JSON to Array
$array = $this->unserialize($implode);
if(empty($array)) {
//Log::set(__METHOD__.LOG_SEP.'Invalid JSON file: '.$file.', cannot be decoded. Check the file content.');
}
else {
if (empty($array)) {
$this->db = array();
$this->dbBackup = array();
} else {
$this->db = $array;
$this->dbBackup = $array;
}
@ -45,32 +44,29 @@ class dbJSON
public function restoreDB()
{
$this->db = $this->dbBackup;
return true;
}
// Returns the amount of database items.
// Returns the amount of rows in the database
public function count()
{
return count($this->db);
}
// Returns the value from the field.
// Returns the value from the field
public function getField($field)
{
if (isset($this->db[$field])) {
return $this->db[$field];
}
return $this->dbFields[$field]['value'];
}
// Save the JSON file.
// Save the JSON file
public function save()
{
$data = '';
if($this->firstLine) {
if ($this->firstLine) {
$data = "<?php defined('BLUDIT') or die('Bludit CMS.'); ?>".PHP_EOL;
}
@ -81,33 +77,37 @@ class dbJSON
$this->dbBackup = $this->db;
// LOCK_EX flag to prevent anyone else writing to the file at the same time.
if( file_put_contents($this->file, $data, LOCK_EX) ) {
if (file_put_contents($this->file, $data, LOCK_EX)) {
return true;
}
else {
Log::set(__METHOD__.LOG_SEP.'Error occurred when trying to save the database file.');
} else {
Log::set(__METHOD__.LOG_SEP.'Error occurred when trying to save the database file.', LOG_TYPE_ERROR);
return false;
}
}
// Returns a JSON encoded string on success or FALSE on failure.
// Returns a JSON encoded string on success or FALSE on failure
private function serialize($data)
{
return json_encode($data, JSON_PRETTY_PRINT);
if (DEBUG_MODE) {
return json_encode($data, JSON_PRETTY_PRINT);
}
return json_encode($data);
}
// Returns the value encoded in json in appropriate PHP type.
// Returns the value encoded in json in appropriate PHP type
private function unserialize($data)
{
// NULL is returned if the json cannot be decoded.
// NULL is returned if the json cannot be decoded
$decode = json_decode($data, true);
// If NULL returns false.
if(empty($decode)) {
if (empty($decode)) {
return false;
}
return $decode;
}
public function getDB()
{
return $this->db;
}
}

View File

@ -19,9 +19,9 @@ checkRole(array('admin'));
// ============================================================================
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if (isset($_POST['delete'])) {
if ($_POST['action']=='delete') {
deleteCategory($_POST);
} elseif (isset($_POST['edit'])) {
} elseif ($_POST['action']=='edit') {
editCategory($_POST);
}

View File

@ -39,14 +39,16 @@ if ($_SERVER['REQUEST_METHOD'] == 'POST') {
// Main after POST
// ============================================================================
$username = $layout['parameters'];
// Prevent non-administrators to change other users
if ($login->role()!=='admin') {
$layout['parameters'] = $login->username();
$username = $login->username();
}
// Get the user to edit
$user = $dbUsers->get($layout['parameters']);
if ($user===false) {
try {
$user = new User($username);
} catch (Exception $e) {
Redirect::page('users');
}

View File

@ -25,6 +25,12 @@ function checkLogin($args)
}
// Renew the token. This token will be the same inside the session for multiple forms.
$security->generateTokenCSRF();
// Users with the role reader do not need access to dashboard
if ($login->role()=='reader') {
Redirect::home();
}
Redirect::page('dashboard');
return true;
}

View File

@ -4,6 +4,8 @@
// Check role
// ============================================================================
checkRole(array('admin', 'moderator', 'editor'));
// ============================================================================
// Functions
// ============================================================================

View File

@ -33,9 +33,10 @@ if ($login->role()!=='admin') {
$layout['parameters'] = $login->username();
}
// Get the user to edit
$user = $dbUsers->get($layout['parameters']);
if ($user===false) {
try {
$username = $layout['parameters'];
$user = new User($username);
} catch (Exception $e) {
Redirect::page('users');
}

View File

@ -2,6 +2,37 @@
class Bootstrap {
public static function modal($args) {
$buttonSecondary = $args['buttonSecondary'];
$buttonSecondaryClass = $args['buttonSecondaryClass'];
$buttonPrimary = $args['buttonPrimary'];
$buttonPrimaryClass = $args['buttonPrimaryClass'];
$modalText = $args['modalText'];
$modalTitle = $args['modalTitle'];
$modalId = $args['modalId'];
return <<<EOF
<div id="$modalId" class="modal fade" tabindex="-1" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-body">
<h3>$modalTitle</h3>
<p>$modalText</p>
</div>
<div class="modal-footer">
<button type="button" class="$buttonSecondaryClass btn btn-secondary" data-dismiss="modal">$buttonSecondary</button>
<button type="button" class="$buttonPrimaryClass btn btn-primary">$buttonPrimary</button>
</div>
</div>
</div>
</div>
EOF;
}
public static function link($args)
{
$options = 'href="'.$args['href'].'"';

View File

@ -2,13 +2,18 @@
echo Bootstrap::pageTitle(array('title'=>$L->g('Edit Category'), 'icon'=>'tags'));
echo Bootstrap::formOpen(array());
echo Bootstrap::formOpen(array('id'=>'jsform'));
echo Bootstrap::formInputHidden(array(
'name'=>'tokenCSRF',
'value'=>$security->getTokenCSRF()
));
echo Bootstrap::formInputHidden(array(
'name'=>'action',
'value'=>'edit'
));
echo Bootstrap::formInputHidden(array(
'name'=>'oldKey',
'value'=>$categoryMap['key']
@ -44,10 +49,34 @@ echo Bootstrap::formOpen(array());
echo '
<div class="form-group mt-4">
<button type="submit" class="btn btn-primary mr-2" name="edit">'.$L->g('Save').'</button>
<button type="submit" class="btn btn-secondary mr-2" name="delete">'.$L->g('Delete').'</button>
<button type="submit" class="btn btn-primary">'.$L->g('Save').'</button>
<a class="btn btn-secondary" href="'.HTML_PATH_ADMIN_ROOT.'categories" role="button">'.$L->g('Cancel').'</a>
<button type="button" class="btn btn-secondary" data-toggle="modal" data-target="#jsdeleteModal">'.$L->g('Delete').'</button>
</div>
';
echo Bootstrap::formClose();
?>
<!-- Modal for delete category -->
<?php
echo Bootstrap::modal(array(
'buttonPrimary'=>'Delete',
'buttonPrimaryClass'=>'jsbuttonDeleteAccept',
'buttonSecondary'=>'Cancel',
'buttonSecondaryClass'=>'',
'modalTitle'=>'Delete category',
'modalText'=>'Are you sure you want to delete the category ?',
'modalId'=>'jsdeleteModal'
));
?>
<script>
$(document).ready(function() {
// Delete content
$(".jsbuttonDeleteAccept").on("click", function() {
$("#jsaction").val("delete");
$("#jsform").submit();
});
});
</script>

View File

@ -88,7 +88,7 @@
<a href="<?php echo HTML_PATH_ADMIN_ROOT ?>dashboard" class="btn btn-secondary"><?php echo $L->g('Cancel') ?></a>
<?php
if (count($page->children())===0) {
echo '<button type="button" class="jsbuttonDelete btn btn-secondary">'.$L->g('Delete').'</button>';
echo '<button type="button" class="btn btn-secondary" data-toggle="modal" data-target="#jsdeletePageModal">'.$L->g('Delete').'</button>';
}
?>
</div>
@ -249,6 +249,28 @@
?>
</div>
<!-- Modal for delete page -->
<?php echo Bootstrap::modal(array(
'buttonPrimary'=>'Delete',
'buttonPrimaryClass'=>'jsbuttonDeleteAccept',
'buttonSecondary'=>'Cancel',
'buttonSecondaryClass'=>'',
'modalTitle'=>'Delete content',
'modalText'=>'Are you sure you want to delete: <b>'.$page->title().'</b>',
'modalId'=>'jsdeletePageModal'
));
?>
<script>
$(document).ready(function() {
// Delete content
$(".jsbuttonDeleteAccept").on("click", function() {
$("#jstype").val("delete");
$("#jscontent").val("");
$("#jsform").submit();
});
});
</script>
<!-- Modal for Categories -->
<div id="jscategoryModal" class="modal fade" tabindex="-1" role="dialog">
<div class="modal-dialog">
@ -369,13 +391,6 @@ $(document).ready(function() {
$("#jsform").submit();
});
// Button Delete
$(".jsbuttonDelete").on("click", function() {
$("#jstype").val("delete");
$("#jscontent").val("");
$("#jsform").submit();
});
// External cover image
$("#jsexternalCoverImage").change(function() {
$("#jscoverImage").val( $(this).val() );

View File

@ -28,7 +28,7 @@ echo Bootstrap::formOpen(array());
echo Bootstrap::formSelect(array(
'name'=>'role',
'label'=>$L->g('Role'),
'options'=>array('editor'=>$L->g('Editor'), 'moderator'=>$L->g('Moderator'), 'admin'=>$L->g('Administrator')),
'options'=>array('reader'=>$L->g('Reader'), 'editor'=>$L->g('Editor'), 'moderator'=>$L->g('Moderator'), 'admin'=>$L->g('Administrator')),
'selected'=>$user->role(),
'class'=>'',
'tip'=>''
@ -127,14 +127,6 @@ echo Bootstrap::formOpen(array());
'tip'=>''
));
echo Bootstrap::formInputText(array(
'name'=>'codepen',
'label'=>'Codepen',
'value'=>$user->codepen(),
'class'=>'',
'tip'=>''
));
echo Bootstrap::formInputText(array(
'name'=>'googlePlus',
'label'=>'Google+',
@ -151,6 +143,38 @@ echo Bootstrap::formOpen(array());
'tip'=>''
));
echo Bootstrap::formInputText(array(
'name'=>'codepen',
'label'=>'Codepen',
'value'=>$user->codepen(),
'class'=>'',
'tip'=>''
));
echo Bootstrap::formInputText(array(
'name'=>'linkedin',
'label'=>'Linkedin',
'value'=>$user->linkedin(),
'class'=>'',
'tip'=>''
));
echo Bootstrap::formInputText(array(
'name'=>'github',
'label'=>'Github',
'value'=>$user->github(),
'class'=>'',
'tip'=>''
));
echo Bootstrap::formInputText(array(
'name'=>'gitlab',
'label'=>'Gitlab',
'value'=>$user->gitlab(),
'class'=>'',
'tip'=>''
));
echo '
<div class="form-group mt-4">
<button type="submit" class="btn btn-primary mr-2" name="save">'.$L->g('Save').'</button>

View File

@ -41,8 +41,8 @@ echo Bootstrap::formOpen(array());
echo Bootstrap::formSelect(array(
'name'=>'role',
'label'=>$L->g('Role'),
'options'=>array('editor'=>$L->g('Editor'), 'moderator'=>$L->g('Moderator'), 'admin'=>$L->g('Administrator')),
'selected'=>'editor',
'options'=>array('reader'=>$L->g('Reader'), 'editor'=>$L->g('Editor'), 'moderator'=>$L->g('Moderator'), 'admin'=>$L->g('Administrator')),
'selected'=>'reader',
'class'=>'',
'tip'=>''
));

View File

@ -24,23 +24,30 @@ echo '
<tbody>
';
$users = $dbUsers->getAllUsers();
foreach ($users as $username=>$User) {
echo '<tr>';
echo '<td><a href="'.HTML_PATH_ADMIN_ROOT.'edit-user/'.$username.'">'.$username.'</a></td>';
echo '<td class="d-none d-lg-table-cell">'.$User->firstName().'</td>';
echo '<td class="d-none d-lg-table-cell">'.$User->lastName().'</td>';
echo '<td>'.$User->email().'</td>';
echo '<td>'.($User->enabled()?'<b>'.$L->g('Enabled').'</b>':$L->g('Disabled')).'</td>';
if ($User->role()=='admin') {
echo '<td>'.$L->g('Administrator').'</td>';
} elseif ($User->role()=='moderator') {
echo '<td>'.$L->g('Moderator').'</td>';
} elseif ($User->role()=='editor') {
echo '<td>'.$L->g('Editor').'</td>';
$list = $dbUsers->getAllUsernames();
foreach ($list as $username) {
try {
$user = new User($username);
echo '<tr>';
echo '<td><a href="'.HTML_PATH_ADMIN_ROOT.'edit-user/'.$username.'">'.$username.'</a></td>';
echo '<td class="d-none d-lg-table-cell">'.$user->firstName().'</td>';
echo '<td class="d-none d-lg-table-cell">'.$user->lastName().'</td>';
echo '<td>'.$user->email().'</td>';
echo '<td>'.($user->enabled()?'<b>'.$L->g('Enabled').'</b>':$L->g('Disabled')).'</td>';
if ($user->role()=='admin') {
echo '<td>'.$L->g('Administrator').'</td>';
} elseif ($user->role()=='moderator') {
echo '<td>'.$L->g('Moderator').'</td>';
} elseif ($user->role()=='editor') {
echo '<td>'.$L->g('Editor').'</td>';
} else {
echo '<td>'.$L->g('Reader').'</td>';
}
echo '<td class="d-none d-lg-table-cell">'.Date::format($user->registered(), DB_DATE_FORMAT, ADMIN_PANEL_DATE_FORMAT).'</td>';
echo '</tr>';
} catch (Exception $e) {
// Continue
}
echo '<td class="d-none d-lg-table-cell">'.Date::format($User->registered(), DB_DATE_FORMAT, ADMIN_PANEL_DATE_FORMAT).'</td>';
echo '</tr>';
}
echo '

View File

@ -1,5 +1,12 @@
<?php defined('BLUDIT') or die('Bludit CMS.');
// // Start session if the cookie is defined
// if (Cookie::get('BLUDIT-KEY')) {
// if (!Session::started()) {
// Session::start();
// }
// }
// Load plugins rules
include(PATH_RULES.'60.plugins.php');
@ -32,3 +39,4 @@ Theme::plugins('afterSiteLoad');
// Plugins after all
Theme::plugins('afterAll');

View File

@ -33,6 +33,22 @@ class dbPages extends dbJSON {
return $this->dbFields;
}
// Return an array with the database for a page, FALSE otherwise
public function getPageDB($key)
{
if ($this->exists($key)) {
return $this->db[$key];
}
return false;
}
// Return TRUE if the page exists, FALSE otherwise
public function exists($key)
{
return isset( $this->db[$key] );
}
// Create a new page
// This function returns the key of the new page
public function add($args, $climode=false)
@ -389,16 +405,6 @@ class dbPages extends dbJSON {
return $tmp;
}
// Return an array with the database for a page, FALSE otherwise
public function getPageDB($key)
{
if ($this->exists($key)) {
return $this->db[$key];
}
return false;
}
// Returns the next number of the bigger position
public function nextPositionNumber()
{
@ -515,11 +521,7 @@ class dbPages extends dbJSON {
return $list;
}
// Return TRUE if the page exists, FALSE otherwise
public function exists($key)
{
return isset( $this->db[$key] );
}
public function sortBy()
{
@ -787,12 +789,6 @@ class dbPages extends dbJSON {
return Text::firstCharUp($field).': '.$value;
}
// Returns the database
public function getDB()
{
return $this->db;
}
// Returns an Array, array('tagSlug'=>'tagName')
// (string) $tags, tag list separeted by comma.
public function generateTags($tags)

View File

@ -1,24 +1,26 @@
<?php defined('BLUDIT') or die('Bludit CMS.');
class dbUsers extends dbJSON
{
class dbUsers extends dbJSON {
public $dbFields = array(
'firstName'=> array('inFile'=>false, 'value'=>''),
'lastName'=> array('inFile'=>false, 'value'=>''),
'username'=> array('inFile'=>false, 'value'=>''),
'role'=> array('inFile'=>false, 'value'=>'editor'),
'password'=> array('inFile'=>false, 'value'=>''),
'salt'=> array('inFile'=>false, 'value'=>'!Pink Floyd!Welcome to the machine!'),
'email'=> array('inFile'=>false, 'value'=>''),
'registered'=> array('inFile'=>false, 'value'=>'1985-03-15 10:00'),
'tokenRemember'=> array('inFile'=>false, 'value'=>''),
'tokenAuth'=> array('inFile'=>false, 'value'=>''),
'tokenAuthTTL'=> array('inFile'=>false, 'value'=>'2009-03-15 14:00'),
'twitter'=> array('inFile'=>false, 'value'=>''),
'facebook'=> array('inFile'=>false, 'value'=>''),
'codepen'=> array('inFile'=>false, 'value'=>''),
'googlePlus'=> array('inFile'=>false, 'value'=>''),
'instagram'=> array('inFile'=>false, 'value'=>'')
'firstName'=>'',
'lastName'=>'',
'role'=>'editor', // admin, moderator, editor, reader
'password'=>'',
'salt'=>'!Pink Floyd!Welcome to the machine!',
'email'=>'',
'registered'=>'1985-03-15 10:00',
'tokenRemember'=>'',
'tokenAuth'=>'',
'tokenAuthTTL'=>'2009-03-15 14:00',
'twitter'=>'',
'facebook'=>'',
'googlePlus'=>'',
'instagram'=>'',
'codepen'=>'',
'linkedin'=>'',
'github'=>'',
'gitlab'=>''
);
function __construct()
@ -26,6 +28,26 @@ class dbUsers extends dbJSON
parent::__construct(DB_USERS);
}
public function getDefaultFields()
{
return $this->dbFields;
}
// Return an array with the database of the user, FALSE otherwise
public function getUserDB($username)
{
if ($this->exists($username)) {
return $this->db[$username];
}
return false;
}
// Return TRUE if the user exists, FALSE otherwise
public function exists($username)
{
return isset($this->db[$username]);
}
// Disable the user
public function disableUser($username)
{
@ -33,64 +55,69 @@ class dbUsers extends dbJSON
return $this->save();
}
// Return TRUE if the user exists, FALSE otherwise
public function exists($username)
{
return isset($this->db[$username]);
}
// Create a new user
// Add a new user
public function add($args)
{
$dataForDb = array();
// The username is store as key and not as field
$username = $args['username'];
// Verify arguments with the database fields
foreach ($this->dbFields as $field=>$options) {
// The password is hashed, the password doesn't need to be sanitize in the next step
$password = $args['password'];
$row = array();
foreach ($this->dbFields as $field=>$value) {
if (isset($args[$field])) {
$value = Sanitize::html($args[$field]);
// Sanitize if will be stored on database
$finalValue = Sanitize::html($args[$field]);
} else {
$value = $options['value'];
// Default value for the field if not defined
$finalValue = $value;
}
// Set type
settype($value, gettype($options['value']));
$dataForDb[$field] = $value;
settype($finalValue, gettype($value));
$row[$field] = $finalValue;
}
$dataForDb['registered'] = Date::current(DB_DATE_FORMAT);
$dataForDb['salt'] = $this->generateSalt();
$dataForDb['password'] = $this->generatePasswordHash($dataForDb['password'], $dataForDb['salt']);
$dataForDb['tokenAuth'] = $this->generateAuthToken();
$row['registered'] = Date::current(DB_DATE_FORMAT);
$row['salt'] = $this->generateSalt();
$row['password'] = $this->generatePasswordHash($password, $row['salt']);
$row['tokenAuth'] = $this->generateAuthToken();
// Save the database
$this->db[$dataForDb['username']] = $dataForDb;
$this->db[$username] = $row;
return $this->save();
}
// Set the parameters of a user
// Edit an user
public function set($args)
{
// Current database of the user
$user = $this->db[$args['username']];
// The username is store as key and not as field
$username = $args['username'];
// Verify arguments with the database fields
foreach ($args as $field=>$value) {
if (isset($this->dbFields[$field])) {
$value = Sanitize::html($value);
settype($value, gettype($this->dbFields[$field]['value']));
$user[$field] = $value;
// Current database of the user
$row = $this->db[$username];
foreach ($this->dbFields as $field=>$value) {
if ($field!=='password') {
if (isset($args[$field])) {
// Sanitize if will be stored on database
$finalValue = Sanitize::html($args[$field]);
} else {
// Default value is the current one
$finalValue = $row[$field];
}
settype($finalValue, gettype($value));
$row[$field] = $finalValue;
}
}
// Set a new password
if (!empty($args['password'])) {
$user['salt'] = $this->generateSalt();
$user['password'] = $this->generatePasswordHash($args['password'], $user['salt']);
$user['tokenAuth'] = $this->generateAuthToken();
$row['salt'] = $this->generateSalt();
$row['password'] = $this->generatePasswordHash($args['password'], $row['salt']);
$row['tokenAuth'] = $this->generateAuthToken();
}
// Save the database
$this->db[$args['username']] = $user;
$this->db[$username] = $row;
return $this->save();
}
@ -101,27 +128,6 @@ class dbUsers extends dbJSON
return $this->save();
}
// DEPRECATED
public function getUser($username)
{
return $this->get($username);
}
// Returns an User Object
public function get($username)
{
if ($this->exists($username)) {
$User = new User();
$User->setField('username', $username);
foreach ($this->db[$username] as $key=>$value) {
$User->setField($key, $value);
}
return $User;
}
return false;
}
public function generateAuthToken()
{
return md5( uniqid().time().DOMAIN );
@ -201,26 +207,8 @@ class dbUsers extends dbJSON
return $this->save();
}
// Returns array with the username databases filtered by username, FALSE otherwise
public function getDB($username)
public function getAllUsernames()
{
if ($this->exists($username)) {
return $this->db[$username];
}
return false;
}
public function getAll()
{
return $this->db;
}
public function getAllUsers()
{
$tmp = array();
foreach ($this->db as $username=>$fields) {
$tmp[$username] = $this->getUser($username);
}
return $tmp;
return array_keys($this->db);
}
}

View File

@ -27,7 +27,7 @@ function buildErrorPage() {
$pageNotFound = New PageX(false);
$pageNotFound->setField('title', $language->get('page-not-found'));
$pageNotFound->setField('content', $language->get('page-not-found-content'));
$pageNotFound->setField('user', $dbUsers->getUser('admin'));
$pageNotFound->setField('username', 'admin');
}
return $pageNotFound;
@ -47,8 +47,7 @@ function buildThePage() {
return false;
}
// Check if the page is NOT published
if ( !$page->published() ) {
if ( $page->draft() || $page->scheduled() ) {
$url->setNotFound();
return false;
}
@ -648,6 +647,9 @@ function checkRole($allowRoles, $redirect=true) {
));
Alert::set($Language->g('You do not have sufficient permissions'));
if ($userRole=='reader') {
Redirect::home();
}
Redirect::page('dashboard');
}
return false;
@ -717,14 +719,14 @@ function deleteCategory($args) {
global $syslog;
// Remove the category by key
$dbCategories->remove($args['oldCategoryKey']);
$dbCategories->remove($args['oldKey']);
// Remove the category from the pages ? or keep it if the user want to recovery the category ?
// Add to syslog
$syslog->add(array(
'dictionaryKey'=>'category-deleted',
'notes'=>$args['oldCategoryKey']
'notes'=>$args['oldKey']
));
Alert::set($Language->g('The changes have been saved'));

View File

@ -1,6 +1,6 @@
<?php defined('BLUDIT') or die('Bludit CMS.');
class Session {
class Session {
private static $started = false;
private static $sessionName = 'BLUDIT-KEY';

View File

@ -130,8 +130,9 @@ class Text {
if (EXTREME_FRIENDLY_URL) {
$string = self::lowercase($string);
$string = trim($string, $separator);
$string = preg_replace("/[\/_|+:!@#$%^&*(). -]+/", $separator, $string);
$string = trim($string, '-');
$string = trim($string, $separator);
return $string;
}

View File

@ -104,15 +104,15 @@ class Login {
return false;
}
$user = $this->dbUsers->getDB($username);
if ($user==false) {
Log::set(__METHOD__.LOG_SEP.'Username does not exist: '.$username);
try {
$user = new User($username);
} catch (Exception $e) {
return false;
}
$passwordHash = $this->dbUsers->generatePasswordHash($password, $user['salt']);
if ($passwordHash===$user['password']) {
$this->setLogin($username, $user['role']);
$passwordHash = $this->dbUsers->generatePasswordHash($password, $user->salt());
if ($passwordHash===$user->password()) {
$this->setLogin($username, $user->role());
Log::set(__METHOD__.LOG_SEP.'User logged succeeded by username and password - Username: '.$username);
return true;
}

View File

@ -40,7 +40,6 @@ class PageX {
return false;
}
// Set a field with a value
public function setField($field, $value)
{
$this->vars[$field] = $value;
@ -501,7 +500,7 @@ class PageX {
// $complete = true : full version
public function relativeTime($complete = false) {
$current = new DateTime;
$past = new DateTime($this->getValue('date'));
$past = new DateTime($this->getValue('dateRaw'));
$elapsed = $current->diff($past);
$elapsed->w = floor($elapsed->d / 7);

View File

@ -1,104 +1,143 @@
<?php defined('BLUDIT') or die('Bludit CMS.');
class User
{
public $db;
class User {
private $vars;
public function setField($field, $value)
function __construct($username)
{
$this->db[$field] = $value;
global $dbUsers;
return true;
$this->vars['username'] = $username;
if ($username===false) {
$row = $dbUsers->getDefaultFields();
} else {
if (Text::isEmpty($username) || !$dbUsers->exists($username)) {
$errorMessage = 'User not found in database by username ['.$username.']';
Log::set(__METHOD__.LOG_SEP.$errorMessage);
throw new Exception($errorMessage);
}
$row = $dbUsers->getUserDB($username);
}
foreach ($row as $field=>$value) {
$this->setField($field, $value);
}
}
public function getField($field)
public function getValue($field)
{
if (isset($this->db[$field])) {
return $this->db[$field];
if (isset($this->vars[$field])) {
return $this->vars[$field];
}
return false;
}
// Returns username
public function setField($field, $value)
{
$this->vars[$field] = $value;
return true;
}
public function getDB()
{
return $this->vars;
}
public function username()
{
return $this->getField('username');
return $this->getValue('username');
}
public function firstName()
{
return $this->getField('firstName');
return $this->getValue('firstName');
}
public function lastName()
{
return $this->getField('lastName');
return $this->getValue('lastName');
}
public function tokenAuth()
{
return $this->getField('tokenAuth');
return $this->getValue('tokenAuth');
}
public function role()
{
return $this->getField('role');
return $this->getValue('role');
}
public function password()
{
return $this->getField('password');
return $this->getValue('password');
}
public function enabled()
{
$password = $this->getField('password');
$password = $this->getValue('password');
return $password != '!';
}
public function salt()
{
return $this->getField('salt');
return $this->getValue('salt');
}
public function email()
{
return $this->getField('email');
return $this->getValue('email');
}
public function registered()
{
return $this->getField('registered');
return $this->getValue('registered');
}
public function twitter()
{
return $this->getField('twitter');
return $this->getValue('twitter');
}
public function facebook()
{
return $this->getField('facebook');
return $this->getValue('facebook');
}
public function codepen()
{
return $this->getField('codepen');
return $this->getValue('codepen');
}
public function googlePlus()
{
return $this->getField('googlePlus');
return $this->getValue('googlePlus');
}
public function instagram()
{
return $this->getField('instagram');
return $this->getValue('instagram');
}
public function github()
{
return $this->getValue('github');
}
public function gitlab()
{
return $this->getValue('gitlab');
}
public function linkedin()
{
return $this->getValue('linkedin');
}
public function profilePicture($absolute=true)
{
$filename = $this->getField('username').'.png';
$filename = $this->getValue('username').'.png';
if( !file_exists(PATH_UPLOADS_PROFILES.$filename) ) {
return '#';

View File

@ -161,10 +161,12 @@ EOF;
if (empty($lines)) {
return 0;
}
$login = new Login();
$tmp = array();
foreach ($lines as $line) {
$key = json_decode($line);
$tmp[$key[0]] = true;
$data = json_decode($line);
$hashIP = $data[0];
$tmp[$hashIP] = true;
}
return count($tmp);
}
@ -173,26 +175,18 @@ EOF;
// The line is a json array with the hash IP of the visitor and the time
public function addVisitor()
{
// Exclude administrators visits
global $login;
if ($this->getValue('excludeAdmins') && defined('BLUDIT_PRO')) {
if ($login->role()=='admin') {
return false;
}
if (Cookie::get('BLUDIT-KEY') && defined('BLUDIT_PRO') && $this->getValue('excludeAdmins')) {
return false;
}
$currentTime = Date::current('Y-m-d H:i:s');
$ip = TCP::getIP();
if (empty($ip)) {
$ip = session_id();
}
$hashIP = md5($ip);
$line = json_encode(array($hashIP, $currentTime));
$currentDate = Date::current('Y-m-d');
$file = $this->workspace().$currentDate.'.log';
$logFile = $this->workspace().$currentDate.'.log';
return file_put_contents($file, $line.PHP_EOL, FILE_APPEND | LOCK_EX)!==false;
return file_put_contents($logFile, $line.PHP_EOL, FILE_APPEND | LOCK_EX)!==false;
}
}