Advertisement
Guest User

dbposts.class.php

a guest
Apr 23rd, 2016
121
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 9.59 KB | None | 0 0
  1. <?php defined('BLUDIT') or die('Bludit CMS.');
  2.  
  3. class dbPosts extends dbJSON
  4. {
  5.     private $dbFields = array(
  6.         'title'=>       array('inFile'=>true,   'value'=>''),
  7.         'content'=>     array('inFile'=>true,   'value'=>''),
  8.         'description'=>     array('inFile'=>false,  'value'=>''),
  9.         'username'=>        array('inFile'=>false,  'value'=>''),
  10.         'status'=>      array('inFile'=>false,  'value'=>'draft'), // published, draft, scheduled
  11.         'tags'=>        array('inFile'=>false,  'value'=>array()),
  12.         'allowComments'=>   array('inFile'=>false,  'value'=>false),
  13.         'date'=>        array('inFile'=>false,  'value'=>''),
  14.         'coverImage'=>      array('inFile'=>false,  'value'=>''),
  15.         'checksum'=>        array('inFile'=>false,  'value'=>'')
  16.     );
  17.  
  18.     private $numberPosts = array(
  19.         'total'=>0,
  20.         'published'=>0
  21.     );
  22.  
  23.     function __construct()
  24.     {
  25.         parent::__construct(PATH_DATABASES.'posts.php');
  26.  
  27.         $this->numberPosts['total'] = count($this->db);
  28.     }
  29.  
  30.     public function numberPost($total=false)
  31.     {
  32.         if($total) {
  33.             return $this->numberPosts['total'];
  34.         }
  35.  
  36.         return $this->numberPosts['published'];
  37.     }
  38.  
  39.     // Returns the database
  40.     public function getDB()
  41.     {
  42.         return $this->db;
  43.     }
  44.  
  45.     // Return an array with the post's database, FALSE otherwise.
  46.     public function getPostDB($key)
  47.     {
  48.         if($this->postExists($key)) {
  49.             return $this->db[$key];
  50.         }
  51.  
  52.         return false;
  53.     }
  54.  
  55.     public function setPostDb($key, $field, $value)
  56.     {
  57.         if($this->postExists($key)) {
  58.             $this->db[$key][$field] = $value;
  59.         }
  60.  
  61.         return false;
  62.     }
  63.  
  64.     // Return TRUE if the post exists, FALSE otherwise.
  65.     public function postExists($key)
  66.     {
  67.         return isset($this->db[$key]);
  68.     }
  69.  
  70.     // Generate a valid Key/Slug.
  71.     public function generateKey($text, $oldKey='')
  72.     {
  73.         if(Text::isEmpty($text)) {
  74.             $text = 'empty';
  75.         }
  76.  
  77.         $newKey = Text::cleanUrl($text);
  78.  
  79.         if($newKey===$oldKey) {
  80.             return $newKey;
  81.         }
  82.  
  83.         // Verify if the key is already been used.
  84.         if( isset($this->db[$newKey]) )
  85.         {
  86.             if( !Text::endsWithNumeric($newKey) ) {
  87.                 $newKey = $newKey.'-0';
  88.             }
  89.  
  90.             while( isset($this->db[$newKey]) ) {
  91.                 $newKey++;
  92.             }
  93.         }
  94.  
  95.         return $newKey;
  96.     }
  97.  
  98.     public function add($args)
  99.     {
  100.         $dataForDb = array();   // This data will be saved in the database
  101.         $dataForFile = array(); // This data will be saved in the file
  102.         $currentDate = Date::current(DB_DATE_FORMAT);
  103.  
  104.         // Generate the database key.
  105.         $key = $this->generateKey($args['slug']);
  106.  
  107.         // The user is always who is loggued.
  108.         $args['username'] = Session::get('username');
  109.         if( Text::isEmpty($args['username']) ) {
  110.             Log::set(__METHOD__.LOG_SEP.'The session does not have the username.');
  111.             return false;
  112.         }
  113.  
  114.         // If the date is not valid, then set the current date.
  115.         if(!Valid::date($args['date'], DB_DATE_FORMAT)) {
  116.             $args['date'] = $currentDate;
  117.         }
  118.  
  119.         // Schedule post ?
  120.         if( ($args['date']>$currentDate) && ($args['status']=='published') ) {
  121.             $args['status'] = 'scheduled';
  122.         }
  123.  
  124.         // Verify arguments with the database fields.
  125.         foreach($this->dbFields as $field=>$options)
  126.         {
  127.             // If the field is in the arguments.
  128.             if( isset($args[$field]) )
  129.             {
  130.                 if($field=='tags') {
  131.                     $tmpValue = $this->generateTags($args['tags']);
  132.                 }
  133.                 else {
  134.                     // Sanitize if will be saved on database.
  135.                     if( !$options['inFile'] ) {
  136.                         $tmpValue = Sanitize::html($args[$field]);
  137.                     }
  138.                     else {
  139.                         $tmpValue = $args[$field];
  140.                     }
  141.                 }
  142.             }
  143.             // Default value if not in the arguments.
  144.             else
  145.             {
  146.                 $tmpValue = $options['value'];
  147.             }
  148.  
  149.             // Check where the field will be written, if in the file or in the database.
  150.             if($options['inFile']) {
  151.                 $dataForFile[$field] = Text::firstCharUp($field).': '.$tmpValue;
  152.             }
  153.             else
  154.             {
  155.                 // Set type
  156.                 settype($tmpValue, gettype($options['value']));
  157.  
  158.                 // Save on database
  159.                 $dataForDb[$field] = $tmpValue;
  160.             }
  161.         }
  162.  
  163.         // Create Hash
  164.         $serialize = serialize($dataForDb+$dataForFile);
  165.         $dataForDb['checksum'] = sha1($serialize);
  166.  
  167.         // Make the directory.
  168.         if( Filesystem::mkdir(PATH_POSTS.$key) === false ) {
  169.             Log::set(__METHOD__.LOG_SEP.'Error occurred when trying to create the directory '.PATH_POSTS.$key);
  170.             return false;
  171.         }
  172.  
  173.         // Make the index.txt and save the file.
  174.         $data = implode("\n", $dataForFile);
  175.         if( file_put_contents(PATH_POSTS.$key.DS.'index.txt', $data) === false ) {
  176.             Log::set(__METHOD__.LOG_SEP.'Error occurred when trying to put the content in the file index.txt');
  177.             return false;
  178.         }
  179.  
  180.         // Save the database
  181.         $this->db[$key] = $dataForDb;
  182.  
  183.         // Sort posts before save.
  184.         $this->sortByDate();
  185.  
  186.         if( $this->save() === false ) {
  187.             Log::set(__METHOD__.LOG_SEP.'Error occurred when trying to save the database file.');
  188.             return false;
  189.         }
  190.  
  191.         return $key;
  192.     }
  193.  
  194.     public function edit($args)
  195.     {
  196.         if( $this->delete($args['key']) ) {
  197.             return $this->add($args);
  198.         }
  199.  
  200.         Log::set(__METHOD__.LOG_SEP.'Error occurred when trying to delete the post.');
  201.         return false;
  202.     }
  203.  
  204.     public function delete($key)
  205.     {
  206.         // Post doesn't exist in database.
  207.         if(!$this->postExists($key)) {
  208.             Log::set(__METHOD__.LOG_SEP.'The post does not exist. Key: '.$key);
  209.         }
  210.  
  211.         // Delete the index.txt file.
  212.         if( Filesystem::rmfile(PATH_POSTS.$key.DS.'index.txt') === false ) {
  213.             Log::set(__METHOD__.LOG_SEP.'Error occurred when trying to delete the file index.txt');
  214.         }
  215.  
  216.         // Delete the directory.
  217.         if( Filesystem::rmdir(PATH_POSTS.$key) === false ) {
  218.             Log::set(__METHOD__.LOG_SEP.'Error occurred when trying to delete the directory '.PATH_POSTS.$key);
  219.         }
  220.  
  221.         // Remove from database.
  222.         unset($this->db[$key]);
  223.  
  224.         // Save the database.
  225.         if( $this->save() === false ) {
  226.             Log::set(__METHOD__.LOG_SEP.'Error occurred when trying to save the database file.');
  227.         }
  228.  
  229.         return true;
  230.     }
  231.  
  232.     // Returns an array with a list of posts keys, filtered by a page number.
  233.     public function getList($pageNumber, $postPerPage, $removeUnpublished=true)
  234.     {
  235.         $totalPosts = $this->numberPosts['total'];
  236.  
  237.         // Remove the unpublished posts.
  238.         if($removeUnpublished) {
  239.             $this->removeUnpublished();
  240.             $totalPosts = $this->numberPosts['published'];
  241.         }
  242.  
  243.         $init = (int) $postPerPage * $pageNumber;
  244.         $end  = (int) min( ($init + $postPerPage - 1), $totalPosts - 1 );
  245.         $outrange = $init<0 ? true : $init>$end;
  246.  
  247.         if(!$outrange) {
  248.             $tmp = array_slice($this->db, $init, $postPerPage, true);
  249.  
  250.             // Restore the database because we delete the unpublished posts.
  251.             $this->restoreDB();
  252.  
  253.             return $tmp;
  254.         }
  255.  
  256.         return array();
  257.     }
  258.  
  259.     // Delete all posts from an user.
  260.     public function deletePostsByUser($username)
  261.     {
  262.         foreach($this->db as $key=>$value)
  263.         {
  264.             if($value['username']==$username) {
  265.                 unset($this->db[$key]);
  266.             }
  267.         }
  268.  
  269.         // Save the database.
  270.         if( $this->save() === false ) {
  271.             Log::set(__METHOD__.LOG_SEP.'Error occurred when trying to save the database file.');
  272.             return false;
  273.         }
  274.  
  275.         Log::set(__METHOD__.LOG_SEP.'Posts from the user '.$username.' were delete.');
  276.         return true;
  277.     }
  278.  
  279.     // Link-up all posts from an user to another user.
  280.     public function linkPostsToUser($oldUsername, $newUsername)
  281.     {
  282.         foreach($this->db as $key=>$value)
  283.         {
  284.             if($value['username']==$oldUsername) {
  285.                 $this->db[$key]['username'] = $newUsername;
  286.             }
  287.         }
  288.  
  289.         // Sort posts before save.
  290.         $this->sortByDate();
  291.  
  292.         // Save the database.
  293.         if( $this->save() === false ) {
  294.             Log::set(__METHOD__.LOG_SEP.'Error occurred when trying to save the database file.');
  295.             return false;
  296.         }
  297.  
  298.         Log::set(__METHOD__.LOG_SEP.'Posts linked to another user.');
  299.         return true;
  300.     }
  301.  
  302.     // Remove unpublished posts, status != published.
  303.     public function removeUnpublished()
  304.     {
  305.         foreach($this->db as $key=>$values)
  306.         {
  307.             if($values['status']!='published') {
  308.                 unset($this->db[$key]);
  309.             }
  310.         }
  311.  
  312.         $this->numberPosts['published'] = count($this->db);
  313.  
  314.         return true;
  315.     }
  316.  
  317.     // Return TRUE if there are new posts published, FALSE otherwise.
  318.     public function scheduler()
  319.     {
  320.         // Get current date.
  321.         $currentDate = Date::current(DB_DATE_FORMAT);
  322.  
  323.         $saveDatabase = false;
  324.  
  325.         // Check scheduled posts
  326.         foreach($this->db as $postKey=>$values)
  327.         {
  328.             if($values['status']=='scheduled')
  329.             {
  330.                 // Publish post.
  331.                 if($values['date']<=$currentDate) {
  332.                     $this->db[$postKey]['status'] = 'published';
  333.                     $saveDatabase = true;
  334.                 }
  335.             }
  336.             elseif($values['status']=='published') {
  337.                 break;
  338.             }
  339.         }
  340.  
  341.         // Save the database ?
  342.         if($saveDatabase)
  343.         {
  344.             if( $this->save() === false ) {
  345.                 Log::set(__METHOD__.LOG_SEP.'Error occurred when trying to save the database file.');
  346.                 return false;
  347.             }
  348.  
  349.             Log::set(__METHOD__.LOG_SEP.'New post published from scheduler.');
  350.             return true;
  351.         }
  352.  
  353.         return false;
  354.     }
  355.  
  356.     // Returns an Array, array('tagSlug'=>'tagName')
  357.     // (string) $tags, tag list separeted by comma.
  358.     public function generateTags($tags)
  359.     {
  360.         $tmp = array();
  361.  
  362.         $tags = trim($tags);
  363.  
  364.         if(empty($tags)) {
  365.             return $tmp;
  366.         }
  367.  
  368.         // Make array
  369.         $tags = explode(',', $tags);
  370.  
  371.         foreach($tags as $tag)
  372.         {
  373.             $tag = trim($tag);
  374.             $tagKey = Text::cleanUrl($tag);
  375.             $tmp[$tagKey] = $tag;
  376.         }
  377.  
  378.         return $tmp;
  379.     }
  380.  
  381.     // Sort posts by date.
  382.     public function sortByDate($HighToLow=true)
  383.     {
  384.         if($HighToLow) {
  385.             uasort($this->db, array($this, 'sortHighToLow'));
  386.         }
  387.         else {
  388.             uasort($this->db, array($this, 'sortLowToHigh'));
  389.         }
  390.  
  391.         return true;
  392.     }
  393.  
  394.     private function sortLowToHigh($a, $b) {
  395.         return $a['date']>$b['date'];
  396.     }
  397.  
  398.     private function sortHighToLow($a, $b) {
  399.         return $a['date']<$b['date'];
  400.     }
  401.  
  402.     // Return TRUE if there are new posts or orphan post deleted, FALSE otherwise.
  403.     public function regenerateCli()
  404.     {
  405.         return false;
  406.     }
  407.  
  408. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement