<?php
/**
 *
 * @category        modules
 * @package         news
 * @author          WebsiteBaker Project
 * @copyright       WebsiteBaker Org. e.V.
 * @link            http://websitebaker.org/
 * @license         http://www.gnu.org/licenses/gpl.html
 * @platform        WebsiteBaker 2.8.3
 * @requirements    PHP 5.3.6 and higher
 * @version         $Id: save_post.php 2 2017-07-02 15:14:29Z Manuela $
 * @filesource      $HeadURL: svn://isteam.dynxs.de/wb/2.10.x/trunk/modules/news/save_post.php $
 * @lastmodified    $Date: 2017-07-02 17:14:29 +0200 (Sun, 02 Jul 2017) $
 *
 */

   function createNewsAccessFile($newLink, $oldLink, $page_id, $section_id, $post_id)
   {
      global $admin, $MESSAGE;
      $sPagesPath = WB_PATH.PAGES_DIRECTORY;
      $sPostsPath = $sPagesPath.'/posts';
   // create /posts/ - directory if not exists
      if(!file_exists($sPostsPath)) {
         if(is_writable($sPagesPath)) {
            make_dir(WB_PATH.PAGES_DIRECTORY.'/posts/');
         }else {
            $admin->print_error($MESSAGE['PAGES_CANNOT_CREATE_ACCESS_FILE']);
         }
      }
   // check if /posts/ - dir is writable
      if(!is_writable($sPostsPath.'/')) {
         $admin->print_error($MESSAGE['PAGES_CANNOT_CREATE_ACCESS_FILE']);
      }
/*
   // delete old accessfile if link has changed
    if (($newLink != $oldLink) && (is_writable($sPostsPath.$oldLink.PAGE_EXTENSION))) {
       if (!unlink($sPostsPath.$oldLink.PAGE_EXTENSION)) {
          $admin->print_error($MESSAGE['PAGES_CANNOT_DELETE_ACCESS_FILE'].' - '.$oldLink);
       }
    }
*/
    // delete old accessfile if link has changed
    if (($newLink != $oldLink) && (is_writable($sPagesPath.$oldLink.PAGE_EXTENSION))) {
        if (!unlink($sPagesPath.$oldLink.PAGE_EXTENSION)) {
          $admin->print_error($MESSAGE['PAGES_CANNOT_DELETE_ACCESS_FILE'].' - '.$oldLink);
        }
    }
   // all ok, now create new accessfile
      $newFile = $sPagesPath.$newLink.PAGE_EXTENSION;
      // $backSteps = preg_replace('/^'.preg_quote(WB_PATH).'/', '', $sPostsPath);
      $backSteps = preg_replace('@^'.preg_quote(WB_PATH).'@', '', $sPostsPath);
      $backSteps = str_repeat( '../', substr_count($backSteps, '/'));
      $content =
         '<?php'."\n".
         '// *** This file is generated by WebsiteBaker Ver.'.WB_VERSION."\n".
         '// *** Creation date: '.date('c')."\n".
         '// *** Do not modify this file manually'."\n".
         '// *** WB will rebuild this file from time to time!!'."\n".
         '// *************************************************'."\n".
         "\t".'$page_id      = '.$page_id.';'."\n".
         "\t".'$section_id   = '.$section_id.';'."\n".
         "\t".'$post_id      = '.$post_id.';'."\n".
         "\t".'$post_section = '.$section_id.';'."\n".
//         "\t".'define(\'POST_SECTION\', '.$section_id.');'."\n".
//         "\t".'define(\'POST_ID\',      '.$post_id.');'."\n".
         "\t".'require(\''.$backSteps.'index.php\');'."\n".
         '// *************************************************'."\n";
      if( file_put_contents($newFile, $content) !== false ) {
      // Chmod the file
         change_mode($newFile);
      }else {
         $admin->print_error($MESSAGE['PAGES_CANNOT_CREATE_ACCESS_FILE'],ADMIN_URL.'/pages/modify.php?page_id='.$page_id);
         // $admin->print_error($MESSAGE['PAGES_CANNOT_CREATE_ACCESS_FILE'].': '.$newFile);

      }
   } // end of function createNewsAccessFile
/* ************************************************************************** */
if ( !defined( 'WB_PATH' ) ){ require( dirname(dirname((__DIR__))).'/config.php' ); }
   require_once(WB_PATH."/include/jscalendar/jscalendar-functions.php");
// Get post_id
   if(!isset($_POST['post_id']) OR !is_numeric($_POST['post_id'])) {
      header("Location: ".ADMIN_URL."/pages/index.php");
      exit( 0 );
   }else {
      $post_id = intval($_POST['post_id']);
   }

   $admin_header = false;
   // Tells script to update when this page was last updated
   $update_when_modified = true;
   // Include WB admin wrapper script
   require(WB_PATH.'/modules/admin.php');

   if (!$admin->checkFTAN()) {
      $admin->print_header();
      $admin->print_error($MESSAGE['GENERIC_SECURITY_ACCESS'],
                          ADMIN_URL.'/pages/modify.php?page_id='.$page_id );
   }
   $admin->print_header();

// Validate all fields
   if($admin->get_post('title') == '' AND $admin->get_post('url') == '') {
        $recallUrl = WB_URL.'/modules/news/modify_post.php?page_id='.$page_id.
                   '&section_id='.$section_id.'&post_id='.$admin->getIDKEY($post_id);
      $admin->print_error($MESSAGE['GENERIC_FILL_IN_ALL'], $recallUrl);
   }else {
      $title      = $admin->StripCodeFromText($admin->get_post('title'));
      $short      = $admin->get_post('short');
      $long       = $admin->get_post('long');
      $commenting = $database->escapeString($admin->get_post('commenting'));
      $active     = intval($admin->get_post('active'));
      $old_link   = $admin->get_post('link');
      $group_id   = intval($admin->get_post('group'));
   }
/*
    $sMediaUrl = WB_URL.MEDIA_DIRECTORY;
    $searchfor = '@(<[^>]*=\s*")('.preg_quote($sMediaUrl).')([^">]*".*>)@siU';
    $short = preg_replace($searchfor, '$1{SYSVAR:MEDIA_REL}$3', $short);
    $long  = preg_replace($searchfor, '$1{SYSVAR:MEDIA_REL}$3', $long);
*/
    $sRelUrl = preg_replace('/^https?:\/\/[^\/]+(.*)/is', '\1', WB_URL);
    $sDocumentRootUrl = str_replace($sRelUrl, '', WB_URL);
    $sMediaUrl = WB_URL.MEDIA_DIRECTORY;
    $aPatterns = array(
        '/(<[^>]*?=\s*\")(\/+)([^\"]*?\"[^>]*?)/is',
        '/(<[^>]*=\s*")('.preg_quote($sMediaUrl, '/').')([^">]*".*>)/siU'
    );
    $aReplacements = array(
        '\1'.$sDocumentRootUrl.'/\3',
        '$1{SYSVAR:MEDIA_REL}$3'
    );
    $short = preg_replace($aPatterns, $aReplacements, $short);
    $long = preg_replace($aPatterns, $aReplacements, $long);
/*
// Get page link URL
    $sql = 'SELECT `link` FROM `'.TABLE_PREFIX.'pages` WHERE `page_id`='.(int)$page_id;
*/
// Get post link URL 
$sql = 'SELECT `link` FROM `'.TABLE_PREFIX.'mod_news_posts` WHERE `post_id`='.$post_id;
$oldLink = $database->get_one($sql);

// Include WB functions file
    require(WB_PATH.'/framework/functions.php');
// Work-out what the link should be
    $newLink = '/posts/'.page_filename($title).PAGE_SPACER.$post_id;
// create new accessfile
    createNewsAccessFile($newLink, $oldLink, $page_id, $section_id, $post_id);
$now = time();
// get publisedwhen and publisheduntil
    $publishedwhen = jscalendar_to_timestamp($admin->get_post('publishdate'));
    if($publishedwhen == '' || $publishedwhen < 1) { $publishedwhen=0; }
    $publisheduntil = jscalendar_to_timestamp($admin->get_post('enddate'), $publishedwhen);
    if($publisheduntil == '' || $publisheduntil < 1) { $publisheduntil=0; }
// Update row
    $sql  = 'UPDATE `'.TABLE_PREFIX.'mod_news_posts` SET '
        . '`group_id`='.(int)$group_id.', '
        . '`title`=\''.$database->escapeString($title).'\', '
        . '`link`=\''.$database->escapeString($newLink).'\', '
        . '`content_short`=\''.$database->escapeString($short).'\', '
        . '`content_long`=\''.$database->escapeString($long).'\', '
        . '`commenting`=\''.$database->escapeString($commenting).'\', '
        . '`active`='.$database->escapeString($active).', '
        . '`published_when`='.(int)$publishedwhen.', '
        . '`published_until`='.(int)$publisheduntil.', '
        . '`posted_when`='.$now.', '
        . '`posted_by`='.(int)$admin->get_user_id().' '
        . 'WHERE `post_id`='.$database->escapeString($post_id);
   $database->query($sql);
// Check if there is a db error, otherwise say successful
   if($database->is_error()) {
      $recallUrl = WB_URL.'/modules/news/modify_post.php?page_id='.$page_id.
                '&section_id='.$section_id.'&post_id='.$admin->getIDKEY($post_id);
      $admin->print_error($database->get_error(), $recallUrl);
   }else {
      $admin->print_success($TEXT['SUCCESS'], ADMIN_URL.'/pages/modify.php?page_id='.$page_id);
   }
// Print admin footer
   $admin->print_footer();
