removing posts

This commit is contained in:
Diego 2017-05-12 20:18:44 +02:00
parent aa9ff9d229
commit 20224b03f4
13 changed files with 184 additions and 1177 deletions

View File

@ -0,0 +1,136 @@
<?php defined('BLUDIT') or die('Bludit CMS.');
/*
Database structure
{
"videos": {
"name": "Videos",
"list": [ "my-page", "second-page" ]
},
"pets": {
"name": "Pets",
"list": [ "cats-and-dogs" ]
}
}
*/
class dbList extends dbJSON
{
public $db = array();
function __construct($file)
{
parent::__construct($file);
}
private function getList($key, $amountOfItems, $pageNumber)
{
if( !isset($this->db[$key]) ) {
Log::set(__METHOD__.LOG_SEP.'Error key does not exist '.$key);
return array();
}
$list = $this->db[$key]['list'];
$total = count($list);
$init = (int) $amountOfItems * $pageNumber;
$end = (int) min( ($init + $amountOfItems - 1), $total );
$outrange = $init<0 ? true : $init>$end;
if($outrange) {
Log::set(__METHOD__.LOG_SEP.'Error out of range');
return array();
}
$list = array_flip($list);
return array_slice($list, $init, $amountOfItems, true);
}
public function generateKey($name)
{
return Text::cleanUrl($name);
}
public function add($name)
{
$key = $this->generateKey($name);
if( isset($this->db[$key]) ) {
Log::set(__METHOD__.LOG_SEP.'Error key already exist: '.$key);
return false;
}
$this->db[$key]['name'] = $name;
$this->db[$key]['list'] = array();
$this->save();
return $key;
}
public function remove($key)
{
if( !isset($this->db[$key]) ) {
Log::set(__METHOD__.LOG_SEP.'The key does not exist, key: '.$key);
return false;
}
unset($this->db[$key]);
return $this->save();
}
public function edit($oldKey, $newName)
{
$newKey = $this->generateKey($newName);
if( isset($this->db[$newKey]) ) {
Log::set(__METHOD__.LOG_SEP.'Error the key already exist');
return false;
}
$this->db[$newKey]['name'] = $newName;
$this->db[$newKey]['list'] = $this->db[$oldKey]['list'];
// Remove the old category
unset( $this->db[$oldKey] );
$this->save();
return $newKey;
}
// Returns the name associated to the key, FALSE if the key doesn't exist
public function getName($key)
{
if( isset($this->db[$key]) ) {
return $this->db[$key]['name'];
}
return false;
}
// Returns an array with key=>name of the list
public function getKeyNameArray($sortAlphanumeric=true)
{
$tmp = array();
foreach($this->db as $key=>$fields) {
$tmp[$key] = $fields['name'];
}
// Sort alphanumeric strings, a01, a10, a11, a20
if($sortAlphanumeric) {
natcasesort($tmp);
}
return $tmp;
}
// Returns the amount of items for some key
public function countItems($key)
{
if( isset($this->db[$key]) ) {
return count($this->db[$key]['list']);
}
return 0;
}
}

View File

@ -103,7 +103,7 @@ echo '<div class="bl-publish-sidebar uk-width-2-10">';
HTML::tags(array( HTML::tags(array(
'name'=>'tags', 'name'=>'tags',
'label'=>'', 'label'=>'',
'allTags'=>$dbTags->getAll(), 'allTags'=>$dbTags->getKeyNameArray(),
'selectedTags'=>array() 'selectedTags'=>array()
)); ));

View File

@ -53,6 +53,7 @@ define('DEBUG_FILE', PATH_CONTENT.'debug.txt');
// PAGES DATABASE // PAGES DATABASE
define('DB_PAGES', PATH_DATABASES.'pages.php'); define('DB_PAGES', PATH_DATABASES.'pages.php');
define('DB_SITE', PATH_DATABASES.'site.php'); define('DB_SITE', PATH_DATABASES.'site.php');
define('DB_CATEGORIES', PATH_DATABASES.'categories.php');
// ADMIN URI FILTER // ADMIN URI FILTER
define('ADMIN_URI_FILTER', '/admin/'); define('ADMIN_URI_FILTER', '/admin/');

View File

@ -40,14 +40,15 @@ if( $Url->whereAmI()==='page' ) {
elseif( !$page->published() ) { elseif( !$page->published() ) {
$Url->setNotFound(true); $Url->setNotFound(true);
} }
else {
$pages[0] = $page;
}
} }
elseif( $Url->whereAmI()==='tag' ) { elseif( $Url->whereAmI()==='tag' ) {
$tagKey = $Url->slug(); $pages = buildPagesByTag();
$pages = buildPagesByTag($tagKey);
} }
elseif( $Url->whereAmI()==='category' ) { elseif( $Url->whereAmI()==='category' ) {
$categoryKey = $Url->slug(); $pages = buildPagesByCategory();
$pages = buildPagesByCategory($categoryKey);
} }
elseif( $Url->whereAmI()==='home' ) { elseif( $Url->whereAmI()==='home' ) {
$pages = buildPagesForHome(); $pages = buildPagesForHome();

View File

@ -1,72 +0,0 @@
<?php defined('BLUDIT') or die('Bludit CMS.');
// ============================================================================
// Variables
// ============================================================================
// Array with all posts specified by a filter.
// Filter by page number, by tag, etc.
$posts = array();
// ============================================================================
// Main
// ============================================================================
// Search for changes on posts by the user.
if( CLI_MODE ) {
if($dbPosts->cliMode()) {
reIndexTagsPosts();
}
}
// Execute the scheduler.
if( $dbPosts->scheduler() ) {
// Reindex dbTags.
reIndexTagsPosts();
}
// Build specific post.
if( ($Url->whereAmI()==='post') && ($Url->notFound()===false) )
{
$Post = buildPost( $Url->slug() );
// The post doesn't exist.
if($Post===false)
{
$Url->setNotFound(true);
unset($Post);
}
// The post is not published yet.
elseif( !$Post->published() )
{
$Url->setNotFound(true);
unset($Post);
}
else
{
$posts[0] = $Post;
}
}
// Build posts by specific tag.
elseif( ($Url->whereAmI()==='tag') && ($Url->notFound()===false) )
{
$posts = buildPostsForPage($Url->pageNumber(), $Site->postsPerPage(), true, $Url->slug(), 'tag');
}
// Build posts by specific category.
elseif( ($Url->whereAmI()==='category') && ($Url->notFound()===false) )
{
$posts = buildPostsForPage($Url->pageNumber(), $Site->postsPerPage(), true, $Url->slug(), 'category');
}
// Build posts for homepage or admin area.
else
{
// Posts for admin area.
if($Url->whereAmI()==='admin') {
$posts = buildPostsForPage($Url->pageNumber(), POSTS_PER_PAGE_ADMIN, false);
}
// Posts for home and blog filter.
elseif( ( ($Url->whereAmI()==='home') || ($Url->whereAmI()==='blog') ) && ($Url->notFound()===false) ) {
$posts = buildPostsForPage($Url->pageNumber(), $Site->postsPerPage(), true);
}
}

View File

@ -1,80 +0,0 @@
<?php defined('BLUDIT') or die('Bludit CMS.');
// ============================================================================
// Variables
// ============================================================================
// Array with all pages.
$pages = array();
// Array with all published pages, order by position.
$pagesPublished = array();
// Array with all pages, order by parent.
// array = {
// NO_PARENT_CHAR => array(), all pages parents
// PageParent1 => array(), all children of the parent1
// ... => array(), all children of the parent...
// PageParent9 => array(), all children of the parent9
// }
$pagesParents = array(NO_PARENT_CHAR=>array());
// Array with all published pages, ordery by parent.
$pagesParentsPublished = array();
// Array with all published parent pages
$parents = array();
// ============================================================================
// Main
// ============================================================================
// Search for changes on pages by the user.
if( CLI_MODE ) {
$dbPages->cliMode();
}
// Build specific page.
if( ($Url->whereAmI()==='page') && ($Url->notFound()===false) )
{
$Page = buildPage( $Url->slug() );
// The page doesn't exist.
if($Page===false)
{
$Url->setNotFound(true);
unset($Page);
}
// The page is not published yet.
elseif( !$Page->published() )
{
$Url->setNotFound(true);
unset($Page);
}
}
// Homepage
if( ($Url->whereAmI()==='home') && ($Url->notFound()===false) )
{
// The user defined as homepage a particular page.
if( Text::isNotEmpty( $Site->homepage() ) )
{
$Url->setWhereAmI('page');
$Page = buildPage( $Site->homepage() );
if($Page===false) {
$Url->setWhereAmI('home');
}
}
}
if($Url->notFound())
{
$Url->setWhereAmI('page');
$Page = new Page('error');
}
// Build all pages
$pages = buildAllPages();

View File

@ -19,20 +19,13 @@
if( $_SERVER['REQUEST_METHOD'] == 'POST' ) if( $_SERVER['REQUEST_METHOD'] == 'POST' )
{ {
$token = isset($_POST['tokenCSRF']) ? Sanitize::html($_POST['tokenCSRF']) : false; $token = isset($_POST['tokenCSRF']) ? Sanitize::html($_POST['tokenCSRF']) : false;
if( !$Security->validateTokenCSRF($token) ) {
if( !$Security->validateTokenCSRF($token) )
{
Log::set(__FILE__.LOG_SEP.'Error occurred when trying to validate the tokenCSRF. Token CSRF ID: '.$token); Log::set(__FILE__.LOG_SEP.'Error occurred when trying to validate the tokenCSRF. Token CSRF ID: '.$token);
// Destroy the session.
Session::destroy(); Session::destroy();
Redirect::page('login');
// Redirect to login panel.
Redirect::page('admin', 'login');
} }
else else {
{ unset( $_POST['tokenCSRF'] );
unset($_POST['tokenCSRF']);
} }
} }

View File

@ -1,223 +1,37 @@
<?php defined('BLUDIT') or die('Bludit CMS.'); <?php defined('BLUDIT') or die('Bludit CMS.');
/* class dbCategories extends dbList
Database structure
- To re index the list of posts and pages need to be sorted
{ {
"videos": {
"name": "Videos",
"pages": [ "my-page", "second-page" ]
},
"pets": {
"name": "Pets",
"pages": [ "cats-and-dogs" ]
}
}
*/
class dbCategories extends dbJSON
{
public $dbFields = array();
function __construct() function __construct()
{ {
parent::__construct(PATH_DATABASES.'categories.php'); parent::__construct(DB_CATEGORIES);
} }
private function getByCategory($type='posts', $categoryKey, $amountPerPage, $pageNumber) function countPagesByCategory($key)
{ {
// Check if the category exists return $this->countItems($key);
if( !isset($this->db[$categoryKey]) ) {
Log::set(__METHOD__.LOG_SEP.'Error getting '.$type.' by the category: '.$categoryKey);
return array();
} }
$list = $this->db[$categoryKey][$type]; public function reindex()
$init = (int) $amountPerPage * $pageNumber;
$end = (int) min( ($init + $amountPerPage - 1), count($list) - 1 );
$outrange = $init<0 ? true : $init > $end;
if($outrange) {
Log::set(__METHOD__.LOG_SEP.'Error getting '.$type.' by the category, out of range, pageNumber: '.$pageNumber);
return array();
}
$tmp = array_flip($list);
return array_slice($tmp, $init, $amountPerPage, true);
}
public function getPagesByCategory($categoryKey, $amountPerPage, $pageNumber)
{ {
return $this->getByCategory('pages', $categoryKey, $amountPerPage, $pageNumber); global $dbPages;
}
public function getPostsByCategory($categoryKey, $amountPerPage, $pageNumber) // Foreach category
{
return $this->getByCategory('posts', $categoryKey, $amountPerPage, $pageNumber);
}
private function countByCategory($type='posts', $categoryKey)
{
if( isset($this->db[$categoryKey][$type]) ) {
return count($this->db[$categoryKey][$type]);
}
return 0;
}
public function countPostsByCategory($categoryKey)
{
return $this->countByCategory('posts', $categoryKey);
}
public function countPagesByCategory($categoryKey)
{
return $this->countByCategory('pages', $categoryKey);
}
public function getAll()
{
$tmp = array();
foreach($this->db as $key=>$data) {
$tmp[$key] = $data['name'];
}
// Sort low to high, by value.
natcasesort($tmp);
return $tmp;
}
public function add($category)
{
$categoryKey = $this->generateKey($category);
if( isset($this->db[$categoryKey]) ) {
Log::set(__METHOD__.LOG_SEP.'The category already exist, key: '.$categoryKey.', name: '.$category);
return false;
}
$this->db[$categoryKey]['name'] = $category;
$this->db[$categoryKey]['posts'] = array();
$this->db[$categoryKey]['pages'] = array();
$this->save();
return $categoryKey;
}
public function remove($categoryKey)
{
if( !isset($this->db[$categoryKey]) ) {
Log::set(__METHOD__.LOG_SEP.'The category does not exist, key: '.$categoryKey);
return false;
}
unset($this->db[$categoryKey]);
return $this->save();
}
public function edit($oldCategoryKey, $newCategory)
{
$newCategoryKey = $this->generateKey($newCategory);
if( isset($this->db[$newCategoryKey]) ) {
Log::set(__METHOD__.LOG_SEP.'The category already exist, key: '.$newCategoryKey.', name: '.$newCategory);
return false;
}
// Add the new category with the posts and pages from the old one
$this->db[$newCategoryKey]['name'] = $newCategory;
$this->db[$newCategoryKey]['posts'] = $this->db[$oldCategoryKey]['posts'];
$this->db[$newCategoryKey]['pages'] = $this->db[$oldCategoryKey]['posts'];
// Remove the old category
unset( $this->db[$oldCategoryKey] );
$this->save();
return $newCategoryKey;
}
// Re-generate posts index
// (array) $db, the $db must be sorted by date and the posts published only.
public function reIndexPosts($db)
{
// Clean post list
foreach( $this->db as $key=>$value ) { foreach( $this->db as $key=>$value ) {
$this->db[$key]['posts'] = array(); $this->db[$key]['list'] = array();
} }
// Foreach post in the database // Foreach post in the database
foreach($db as $postKey=>$postData) { $db = $dbPages->getDB();
if( !empty($postData['category']) ) { foreach($db as $pageKey=>$pageFields) {
$categoryKey = $postData['category']; if( !empty($pageFields['category']) ) {
if( isset($this->db[$categoryKey]['posts']) ) { $categoryKey = $pageFields['category'];
array_push($this->db[$categoryKey]['posts'], $postKey); if( isset($this->db[$categoryKey]['list']) ) {
array_push($this->db[$categoryKey]['list'], $pageKey);
} }
} }
} }
return $this->save(); return $this->save();
} }
// Re-generate pages index
// (array) $db, the $db must be sorted by date and the posts published only.
public function reIndexPages($db)
{
// Clean post list
foreach( $this->db as $key=>$value ) {
$this->db[$key]['pages'] = array();
}
// Foreach post in the database
foreach($db as $postKey=>$postData) {
if( !empty($postData['category']) ) {
$categoryKey = $postData['category'];
if( isset($this->db[$categoryKey]['pages']) ) {
array_push($this->db[$categoryKey]['pages'], $postKey);
}
}
}
return $this->save();
}
public function exists($categoryKey)
{
return isset( $this->db[$categoryKey] );
}
public function getName($categoryKey)
{
return $this->db[$categoryKey]['name'];
}
public function generateKey($category)
{
return Text::cleanUrl($category);
}
public function getListOfPosts($pageNumber, $postPerPage, $categoryKey)
{
if( !isset($this->db[$categoryKey]) ) {
Log::set(__METHOD__.LOG_SEP.'Error occurred when trying get the posts list by the category key: '.$categoryKey);
return array();
}
$init = (int) $postPerPage * $pageNumber;
$end = (int) min( ($init + $postPerPage - 1), count($this->db[$categoryKey]['posts']) );
$outrange = $init<0 ? true : $init > $end;
if(!$outrange) {
$list = $this->db[$categoryKey]['posts'];
$tmp = array_flip($list); // Change the posts keys list in the array key.
return array_slice($tmp, $init, $postPerPage, true);
}
Log::set(__METHOD__.LOG_SEP.'Error occurred when trying get the list of posts, out of range?. Pagenumber: '.$pageNumber);
return array();
}
} }

View File

@ -1,578 +0,0 @@
<?php defined('BLUDIT') or die('Bludit CMS.');
class dbPosts extends dbJSON
{
private $dbFields = array(
'title'=> array('inFile'=>true, 'value'=>''),
'content'=> array('inFile'=>true, 'value'=>''),
'description'=> array('inFile'=>false, 'value'=>''),
'username'=> array('inFile'=>false, 'value'=>''),
'status'=> array('inFile'=>false, 'value'=>'draft'), // published, draft, scheduled
'tags'=> array('inFile'=>false, 'value'=>array()),
'allowComments'=> array('inFile'=>false, 'value'=>0),
'date'=> array('inFile'=>false, 'value'=>''),
'dateModified'=> array('inFile'=>false, 'value'=>''),
'coverImage'=> array('inFile'=>false, 'value'=>''),
'md5file'=> array('inFile'=>false, 'value'=>''),
'category'=> array('inFile'=>false, 'value'=>''),
'uuid'=> array('inFile'=>false, 'value'=>'')
);
function __construct()
{
parent::__construct(PATH_DATABASES.'posts.php');
}
// Returns the amount of posts
// $total = TRUE, returns the total of posts
// $total = FALSE, return the amount of published posts
public function numberPost($total=false)
{
// Amount of total posts, published, scheduled and draft
if($total) {
return count($this->db);
}
// Amount of published posts
$i = 0;
foreach($this->db as $values) {
if($values['status']=='published') {
$i++;
}
}
return $i;
}
// Returns the complete database
public function getDB()
{
return $this->db;
}
// Return an array with the post database, FALSE otherwise.
// Filtered by post key
public function getPostDB($key)
{
if($this->postExists($key)) {
return $this->db[$key];
}
return false;
}
public function setPostDb($key, $field, $value)
{
if($this->postExists($key)) {
$this->db[$key][$field] = $value;
}
return false;
}
// Return TRUE if the post exists, FALSE otherwise.
public function postExists($key)
{
return isset( $this->db[$key] );
}
// Generate a valid Key/Slug.
public function generateKey($text, $oldKey='')
{
if(Text::isEmpty($text)) {
$text = 'empty';
}
$newKey = Text::cleanUrl($text);
if($newKey===$oldKey) {
return $newKey;
}
// Verify if the key is already been used.
if( isset($this->db[$newKey]) )
{
if( !Text::endsWithNumeric($newKey) ) {
$newKey = $newKey.'-0';
}
while( isset($this->db[$newKey]) ) {
$newKey++;
}
}
return $newKey;
}
public function add($args)
{
$dataForDb = array(); // This data will be saved in the database
$dataForFile = array(); // This data will be saved in the file
// Current date, format of DB_DATE_FORMAT
$currentDate = Date::current(DB_DATE_FORMAT);
// Generate the database key / index
$key = $this->generateKey($args['slug']);
// Generate UUID
if( empty($args['uuid']) ) {
$args['uuid'] = md5(uniqid());
}
// The user is always who is loggued
$args['username'] = Session::get('username');
if( Text::isEmpty($args['username']) ) {
Log::set(__METHOD__.LOG_SEP.'Session username doesnt exists.');
return false;
}
// If the date is not valid, then set the current date.
if(!Valid::date($args['date'], DB_DATE_FORMAT)) {
$args['date'] = $currentDate;
}
// Schedule post ?
if( ($args['date']>$currentDate) && ($args['status']=='published') ) {
$args['status'] = 'scheduled';
}
// Verify arguments with the database fields
foreach($this->dbFields as $field=>$options)
{
// If the field is in the arguments
if( isset($args[$field]) )
{
if($field=='tags') {
$tmpValue = $this->generateTags($args['tags']);
}
else {
// Where the argument will be stored, database or file
if( !$options['inFile'] ) {
// Sanitize if going to be stored on database
$tmpValue = Sanitize::html($args[$field]);
}
else {
$tmpValue = $args[$field];
}
}
}
else {
// Set a default value if not in the arguments
$tmpValue = $options['value'];
}
// Check where the field will be stored in the file or in the database
if($options['inFile']) {
$dataForFile[$field] = Text::firstCharUp($field).': '.$tmpValue;
}
else {
// Set type
settype($tmpValue, gettype($options['value']));
// Save on database
$dataForDb[$field] = $tmpValue;
}
}
// Create the directory
if( Filesystem::mkdir(PATH_POSTS.$key) === false ) {
Log::set(__METHOD__.LOG_SEP.'Error occurred when trying to create the directory '.PATH_POSTS.$key);
return false;
}
// Make the index.txt and save the file.
$data = implode("\n", $dataForFile);
if( file_put_contents(PATH_POSTS.$key.DS.FILENAME, $data) === false ) {
Log::set(__METHOD__.LOG_SEP.'Error occurred when trying to put the content in the file index.txt');
return false;
}
// Calculate the checksum of the file
$dataForDb['md5file'] = md5_file(PATH_POSTS.$key.DS.FILENAME);
// Insert in the database
$this->db[$key] = $dataForDb;
// Sort database posts before save
$this->sortByDate();
// Save database file
if( $this->save() === false ) {
Log::set(__METHOD__.LOG_SEP.'Error occurred when trying to save the database file.');
return false;
}
return $key;
}
public function edit($args)
{
// Modified date
$args['dateModified'] = Date::current(DB_DATE_FORMAT);
// Keep UUID
$args['uuid'] = $this->db[$args['key']]['uuid'];
if( $this->delete($args['key']) ) {
return $this->add($args);
}
Log::set(__METHOD__.LOG_SEP.'Error occurred when trying to delete the post.');
return false;
}
public function delete($key)
{
// Post doesn't exist in database.
if(!$this->postExists($key)) {
Log::set(__METHOD__.LOG_SEP.'The post does not exist. Key: '.$key);
}
// Delete the index.txt file.
if( Filesystem::rmfile(PATH_POSTS.$key.DS.FILENAME) === false ) {
Log::set(__METHOD__.LOG_SEP.'Error occurred when trying to delete the file index.txt');
}
// Delete the directory.
if( Filesystem::rmdir(PATH_POSTS.$key) === false ) {
Log::set(__METHOD__.LOG_SEP.'Error occurred when trying to delete the directory '.PATH_POSTS.$key);
}
// Remove from database.
unset($this->db[$key]);
// Save the database.
if( $this->save() === false ) {
Log::set(__METHOD__.LOG_SEP.'Error occurred when trying to save the database file.');
}
return true;
}
// Returns an array with a list of posts keys, filtered by a page number.
public function getList($pageNumber, $postPerPage, $removeUnpublished=true)
{
$totalPosts = $this->numberPost(true);
// Remove the unpublished posts.
if($removeUnpublished) {
$this->removeUnpublished();
$totalPosts = $this->numberPost(true);
}
$init = (int) $postPerPage * $pageNumber;
$end = (int) min( ($init + $postPerPage - 1), $totalPosts - 1 );
$outrange = $init<0 ? true : $init>$end;
if(!$outrange) {
$tmp = array_slice($this->db, $init, $postPerPage, true);
// Restore the database because we deleted the unpublished posts.
$this->restoreDB();
return $tmp;
}
return array();
}
// Delete all posts from an user
public function deletePostsByUser($username)
{
foreach($this->db as $key=>$value) {
if($value['username']==$username) {
$this->delete($key);
Log::set(__METHOD__.LOG_SEP.'Post deleted: '.$key);
}
}
Log::set(__METHOD__.LOG_SEP.'Posts from the user '.$username.' were delete.');
return true;
}
// Link-up all posts from an user to another user.
public function linkPostsToUser($oldUsername, $newUsername)
{
foreach($this->db as $key=>$value) {
if($value['username']==$oldUsername) {
$this->db[$key]['username'] = $newUsername;
}
}
// Sort posts before save.
$this->sortByDate();
// Save the database.
if( $this->save() === false ) {
Log::set(__METHOD__.LOG_SEP.'Error occurred when trying to save the database file.');
return false;
}
Log::set(__METHOD__.LOG_SEP.'Posts linked to another user.');
return true;
}
// Remove unpublished posts, status != published.
public function removeUnpublished()
{
foreach($this->db as $key=>$values) {
if($values['status']!='published') {
unset($this->db[$key]);
}
}
return true;
}
// Return TRUE if there are new posts published, FALSE otherwise.
public function scheduler()
{
// Get current date
$currentDate = Date::current(DB_DATE_FORMAT);
$saveDatabase = false;
// Check scheduled posts
foreach($this->db as $postKey=>$values)
{
if($values['status']=='scheduled') {
// Publish post
if($values['date']<=$currentDate) {
$this->db[$postKey]['status'] = 'published';
$saveDatabase = true;
}
}
elseif($values['status']=='published') {
break;
}
}
// Save the database ?
if($saveDatabase)
{
if( $this->save() === false ) {
Log::set(__METHOD__.LOG_SEP.'Error occurred when trying to save the database file.');
return false;
}
Log::set(__METHOD__.LOG_SEP.'New posts published from the scheduler.');
return true;
}
return false;
}
// Returns an Array, array('tagSlug'=>'tagName')
// (string) $tags, tag list separeted by comma.
public function generateTags($tags)
{
$tmp = array();
$tags = trim($tags);
if(empty($tags)) {
return $tmp;
}
// Make array
$tags = explode(',', $tags);
foreach($tags as $tag)
{
$tag = trim($tag);
$tagKey = Text::cleanUrl($tag);
$tmp[$tagKey] = $tag;
}
return $tmp;
}
// Change all posts with the old category key for the new category key
public function changeCategory($oldCategoryKey, $newCategoryKey)
{
foreach($this->db as $key=>$value) {
if($value['category']==$oldCategoryKey) {
$this->db[$key]['category'] = $newCategoryKey;
}
}
// Save database
return $this->save();
}
// Sort posts by date.
public function sortByDate($HighToLow=true)
{
if($HighToLow) {
uasort($this->db, array($this, 'sortHighToLow'));
}
else {
uasort($this->db, array($this, 'sortLowToHigh'));
}
return true;
}
private function sortLowToHigh($a, $b) {
return $a['date']>$b['date'];
}
private function sortHighToLow($a, $b) {
return $a['date']<$b['date'];
}
public function cliMode()
{
// LOG
Log::set('CLI MODE - POSTS - Starting...');
$postList = array();
$postsDirectories = Filesystem::listDirectories(PATH_POSTS);
foreach( $postsDirectories as $directory ) {
if( Sanitize::pathFile($directory.DS.FILENAME) ) {
// The key is the directory name
$key = basename($directory);
// Add the key to the list
$postList[$key] = true;
// Checksum
$checksum = md5_file($directory.DS.FILENAME);
// LOG
Log::set('CLI MODE - Post found, key: '.$key);
if( !isset($this->db[$key]) ) {
// LOG
Log::set('CLI MODE - The post is not in the database, key: '.$key);
// Insert new post
$this->cliModeInsert($key);
}
else {
// If checksum is different, update the post
if( $this->db[$key]['md5file']!==$checksum ) {
// LOG
Log::set('CLI MODE - Different md5 checksum, key: '.$key);
// Update the post
$this->cliModeInsert($key, $update=true);
}
}
}
}
// LOG
Log::set('CLI MODE - Cleaning database...');
foreach( array_diff_key($this->db, $postList) as $key=>$data ) {
// LOG
Log::set('CLI MODE - Removing post from database, key: '.$key);
// Removing the post from database
unset( $this->db[$key] );
}
// Sort posts before save
$this->sortByDate();
// Save the database
$this->save();
// LOG
Log::set('CLI MODE - POSTS - Finishing...');
return true;
}
private function cliModeInsert($key, $update=false)
{
if($update) {
// LOG
Log::set('CLI MODE - cliModeInsert() - Updating the post, key: '.$key);
// Database from the current database
$dataForDb = $this->db[$key];
$dataForDb['dateModified'] = Date::current(DB_DATE_FORMAT);
}
else {
// LOG
Log::set('CLI MODE - cliModeInsert() - Inserting the new post, key: '.$key);
// Database for the new post, fields with the default values
$dataForDb = array();
foreach( $this->dbFields as $field=>$options ) {
if( !$options['inFile'] ) {
$dataForDb[$field] = $options['value'];
}
}
// Fields and value predefined in init.php
$dataForDb['username'] = CLI_USERNAME;
$dataForDb['status'] = CLI_STATUS;
$dataForDb['date'] = Date::current(DB_DATE_FORMAT);
}
// MD5 checksum
$dataForDb['md5file'] = md5_file(PATH_POSTS.$key.DS.FILENAME);
// Generate the Object from the file
$Post = new Post($key);
foreach( $this->dbFields as $field=>$options ) {
if( !$options['inFile'] ) {
// Get the field from the file
// If the field doesn't exist, the function returns FALSE
$data = $Post->getField($field);
if( $data!==false ) {
$tmpValue = '';
if( $field=='tags' ) {
$tmpValue = $this->generateTags($data);
}
elseif( $field=='date' ) {
// Validate format date from file
if( Valid::date($data, DB_DATE_FORMAT) ) {
$tmpValue = $data;
if( $data > $currentDate ) {
$dataForDb['status'] = 'scheduled';
}
}
}
else {
$tmpValue = Sanitize::html($data);
}
settype($tmpValue, gettype($options['value']));
$dataForDb[$field] = $tmpValue;
}
}
}
// Insert row in the database
$this->db[$key] = $dataForDb;
return true;
}
}

View File

@ -1,109 +1,39 @@
<?php defined('BLUDIT') or die('Bludit CMS.'); <?php defined('BLUDIT') or die('Bludit CMS.');
class dbTags extends dbJSON class dbTags extends dbList
{ {
/*
$postsIndex['tag1']['name'] = 'Tag 1';
$postsIndex['tag1']['posts'] = array('post1','post2','post3');
$postsIndex['tag2']['name'] = 'Tag 2';
$postsIndex['tag2']['posts'] = array('post1','post5');
*/
public $dbFields = array(
'postsIndex'=>array('inFile'=>false, 'value'=>array()),
'pagesIndex'=>array('inFile'=>false, 'value'=>array())
);
function __construct() function __construct()
{ {
parent::__construct(PATH_DATABASES.'tags.php'); parent::__construct(DB_TAGS);
} }
public function getTag($slug) { function countPagesByTag($tagKey)
if( isset($this->db['postsIndex'][$slug]['name']) ) {
return $this->db['postsIndex'][$slug]['name'];
}
return '';
}
// Returns an array with all tags names
public function getAll()
{ {
$tmp = array(); return $this->countItems($tagKey);
foreach($this->db['postsIndex'] as $tagSlug=>$tagInfo) {
$tmp[$tagSlug] = $tagInfo['name'];
} }
// Sort low to high, by value. public function reindex()
natcasesort($tmp);
return $tmp;
}
// Returns an array with a list of posts keys, filtered by a page number and a tag key.
public function getList($pageNumber, $postPerPage, $tagKey)
{ {
if( !isset($this->db['postsIndex'][$tagKey]) ) { global $dbPages;
Log::set(__METHOD__.LOG_SEP.'Error occurred when trying get the posts list by the tag key: '.$tagKey);
return array();
}
$init = (int) $postPerPage * $pageNumber; $db = $dbPages->getDB();
$end = (int) min( ($init + $postPerPage - 1), $this->countPostsByTag($tagKey) - 1 );
$outrange = $init<0 ? true : $init > $end;
if(!$outrange) {
$list = $this->db['postsIndex'][$tagKey]['posts'];
$tmp = array_flip($list); // Change the posts keys list in the array key.
return array_slice($tmp, $init, $postPerPage, true);
}
Log::set(__METHOD__.LOG_SEP.'Error occurred when trying get the list of posts, out of range?. Pagenumber: '.$pageNumber);
return array();
}
public function countPostsByTag($tagKey)
{
if( isset($this->db['postsIndex'][$tagKey]) ) {
return count($this->db['postsIndex'][$tagKey]['posts']);
}
return 0;
}
// Regenerate the posts index for each tag.
// (array) $db, the $db must be sorted by date and the posts published only.
public function reindexPosts($db)
{
$tagsIndex = array(); $tagsIndex = array();
// Foreach post foreach($db as $pageKey=>$pageFields) {
foreach($db as $postKey=>$values) $tags = $pageFields['tags'];
{ foreach($tags as $tagKey=>$tagName) {
$tags = $values['tags'];
// Foreach tag from post
foreach($tags as $tagKey=>$tagName)
{
if( isset($tagsIndex[$tagKey]) ) { if( isset($tagsIndex[$tagKey]) ) {
array_push($tagsIndex[$tagKey]['posts'], $postKey); array_push($tagsIndex[$tagKey]['list'], $pageKey);
} }
else { else {
$tagsIndex[$tagKey]['name'] = $tagName; $tagsIndex[$tagKey]['name'] = $tagName;
$tagsIndex[$tagKey]['posts'] = array($postKey); $tagsIndex[$tagKey]['list'] = array($pageKey);
} }
} }
} }
$this->db['postsIndex'] = $tagsIndex; $this->db = $tagsIndex;
return $this->save();
if( $this->save() === false ) {
Log::set(__METHOD__.LOG_SEP.'Error occurred when trying to save the database file.');
return false;
}
return true;
} }
} }

View File

@ -90,13 +90,19 @@ function buildPagesForHome()
return buildPagesFor('home'); return buildPagesFor('home');
} }
function buildPagesByCategory($categoryKey) function buildPagesByCategory()
{ {
global $Url;
$categoryKey = $Url->slug();
return buildPagesFor('category', $categoryKey, false); return buildPagesFor('category', $categoryKey, false);
} }
function buildPagesByTag($tagKey) function buildPagesByTag()
{ {
global $Url;
$tagKey = $Url->slug();
return buildPagesFor('tag', false, $tagKey); return buildPagesFor('tag', false, $tagKey);
} }
@ -142,123 +148,3 @@ function buildPagesFor($for, $categoryKey=false, $tagKey=false)
} }
return $pages; return $pages;
} }
// ---- OLD
function buildPostsForPage($pageNumber=0, $amount=POSTS_PER_PAGE_ADMIN, $removeUnpublished=true, $key=false, $type='tag')
{
global $dbPosts;
global $dbTags;
global $dbCategories;
global $Url;
$posts = array();
if( $type=='tag' && $key ) {
// Get the keys list from tags database, this database is optimized for this case.
$list = $dbTags->getList($pageNumber, $amount, $key);
}
elseif( $type=='category' && $key ) {
$list = $dbCategories->getListOfPosts($pageNumber, $amount, $key);
}
else {
// Get the keys list from posts database.
$list = $dbPosts->getList($pageNumber, $amount, $removeUnpublished);
}
// There are not posts for the page number then set the page notfound
if(empty($list) && $pageNumber>0) {
$Url->setNotFound(true);
}
// Foreach post key, build the post.
foreach($list as $postKey=>$values)
{
$Post = buildPost($postKey);
if($Post!==false) {
array_push($posts, $Post);
}
}
return $posts;
}
// PAGE FUNCTIONS
// ----------------------------------------------------------------------------
function sortPages($a, $b)
{
if ($a['position'] == $b['position']) {
return 0;
}
return ($a['position'] < $b['position']) ? -1 : 1;
}
function buildAllPages()
{
global $pagesParents;
global $pagesParentsPublished;
global $pagesPublished;
global $dbPages;
global $parents;
// Get the page list
$list = $dbPages->getDB();
// Clean pages array.
$pages = array();
// Remove the error page
unset($list['error']);
// Sorte pages
uasort($list, 'sortPages');
foreach($list as $key=>$db)
{
$Page = buildPage($key);
if($Page!==false)
{
// Filter pages, with and without parent
// If the page doesn't have a father, it's a parent page :P
if( $Page->parentKey()===false ) {
// Add the parent key in the dbPages
$dbPages->addParentKey($Page->key());
// Add the page as a parent page in the array
$pagesParents[NO_PARENT_CHAR][$Page->key()] = $Page;
// If the page is published
if($Page->published()) {
$pagesParentsPublished[NO_PARENT_CHAR][$Page->key()] = $Page;
}
}
else {
$pagesParents[$Page->parentKey()][$Page->key()] = $Page;
// If the page is published
if($Page->published()) {
$pagesParentsPublished[$Page->parentKey()][$Page->key()] = $Page;
}
}
// All pages in one array
$pages[$Page->key()] = $Page;
// If the page is published
if($Page->published()) {
$pagesPublished[$Page->parentKey()][$Page->key()] = $Page;
}
}
}
if( isset($pagesParentsPublished[NO_PARENT_CHAR]) ) {
$parents = $pagesParentsPublished[NO_PARENT_CHAR];
}
return $pages;
}

View File

@ -72,7 +72,7 @@ class Theme {
$tmp = $Page->title().' - '.$Site->title(); $tmp = $Page->title().' - '.$Site->title();
} }
elseif( $Url->whereAmI()=='tag' ) { elseif( $Url->whereAmI()=='tag' ) {
$tag = $dbTags->getTag($Url->slug()); $tag = $dbTags->getName($Url->slug());
$tmp = $tag.' - '.$Site->title(); $tmp = $tag.' - '.$Site->title();
} }
else { else {

View File

@ -1,24 +0,0 @@
<?php defined('BLUDIT') or die('Bludit CMS.');
class Post extends Content {
function __construct($key)
{
// Database Key
$this->setField('key', $key);
// Set filterType
$this->setField('filterType', 'post');
parent::__construct(PATH_POSTS.$key.DS);
}
// Returns the post slug
public function slug()
{
return $this->getField('key');
}
}