<?php

/**
 *  @module         news
 *  @version        see info.php of this module
 *  @author         Ryan Djurovich, Rob Smith, Dietrich Roland Pehlke, Christian M. Stefan (Stefek), Jurgen Nijhuis (Argos), LEPTON Project
 *  @copyright      2004-2010 Ryan Djurovich, Rob Smith, Dietrich Roland Pehlke, Christian M. Stefan (Stefek), Jurgen Nijhuis (Argos) 
 *  @copyright      2010-2026 LEPTON Project 
 *  @license        GNU General Public License
 *  @license terms  see info.php of this module
 *  @platform       see info.php of this module
 * 
 */

// include secure.php to protect this file and the whole CMS!
if(!defined("SEC_FILE")){define("SEC_FILE",'/framework/secure.php' );}
if (defined('LEPTON_PATH')) {	
	include LEPTON_PATH.SEC_FILE;
} else {
	$oneback = "../";
	$root = $oneback;
	$level = 1;
	while (($level < 10) && (!file_exists($root.SEC_FILE))) {
		$root .= $oneback;
		$level += 1;
	}
	if (file_exists($root.SEC_FILE)) { 
		include $root.SEC_FILE;   
	} else {
		trigger_error(sprintf("[ <b>%s</b> ] Can't include secure.php!", $_SERVER['SCRIPT_NAME']), E_USER_ERROR);
	}
}
// end include secure file

$database = LEPTON_database::getInstance();
$oNEWS = news_frontend::getInstance();
$oTWIG = lib_twig_box::getInstance();	
$oTWIG->registerModule("news");

// Check if there is a start point defined
$position = filter_input(INPUT_GET,'p', FILTER_SANITIZE_NUMBER_INT) ?? 0 ;

// Get user's username, display name, email, and id - needed for insertion into post info
$users = [];
$all_users = [];
$database->execute_query(
    "SELECT user_id, username, display_name, email FROM ".TABLE_PREFIX."users ",
    true,
    $all_users,
	true
);

if(!empty($all_users)) 
{
    foreach( $all_users as &$user)
    {
        // Insert user info into users array
        $user_id = $user['user_id'];
        $users[$user_id]['username'] = $user['username'];
        $users[$user_id]['display_name'] = $user['display_name'];
        $users[$user_id]['email'] = $user['email'];
    }
}

// Get groups (title, if they are active, and their image [if one has been uploaded])
if (isset($groups))
{
    unset($groups);
}

$groups[0]['title'] = '';
$groups[0]['active'] = true;
$groups[0]['image'] = '';

$all_groups = [];
$database->execute_query(
        "SELECT group_id, title, active FROM ".TABLE_PREFIX."mod_news_groups WHERE page_id = ".$page_id." ORDER BY position ASC",
        true,
        $all_groups,
		true
);

if (!empty($all_groups))
{
    foreach($all_groups as &$group)
    {
        // Insert user info into users array
        $group_id = $group['group_id'];
        $groups[$group_id]['title'] = $group['title'];
        $groups[$group_id]['active'] = $group['active'];
        
        // [2]  init with an empty string/path
        $groups[$group_id]['image'] = '';
        
        // [2.1] look for an (group-)image         
        $aTempTypes = ["jpg", "jpeg", "png", "gif"];
        foreach ($aTempTypes as $sTempType)
        {
            if (file_exists(LEPTON_PATH.MEDIA_DIRECTORY.'/newspics/groups/image'.$group_id.'.'.$sTempType))
            {
                $groups[$group_id]['image'] = LEPTON_URL.MEDIA_DIRECTORY.'/newspics/groups/image'.$group_id.'.'.$sTempType;
                break; // exit this loop
            }
        }
    }
}

/**
 *  Timebase activation or deactivation of the news posts.
 *  Keep in mind that the database class will return an object-instance each time a query.
 *
 */
$current_time = time();
$database->simple_query("UPDATE ".TABLE_PREFIX."mod_news_posts SET active = 0 WHERE published_until > 0 AND published_until <= ".$current_time );
$database->simple_query("UPDATE ".TABLE_PREFIX."mod_news_posts SET active = 1 WHERE (published_when > 0) AND (published_when <= ".$current_time.") AND (published_until > 0) AND (published_until >= ".$current_time.")");

if (ENABLED_CAPTCHA == 0)
{
	$database->simple_query("UPDATE ".TABLE_PREFIX."mod_news_settings set use_captcha = 0 WHERE section_id = ".$section_id);
}


/**
 * Test for "own date format via INTL"
 */
try {
    $oDateUtil = LEPTON_date::getInstance();;
} catch (Exception $e) {
}
if (true === $oDateUtil->intl_installed)
{
	$oDateUtil->sINTLFormat = $oNEWS->language["own_date_full_format"];
}

$oDateUtil->setLanguage([LANGUAGE]);

// Check if we should show the main page or a post itself
if(!defined('POST_ID') || !is_numeric(POST_ID))
{
    // Check if we should only list posts from a certain group
    $iTempGroup = filter_input( INPUT_GET, "g", FILTER_SANITIZE_NUMBER_INT) ?? 0 ;
    $query_extra = ( $iTempGroup > 0 ) 
        ? " AND group_id = ".$iTempGroup." " 
        : ""
        ;

    // Get settings
	$posts_per_page = $database->get_one("SELECT posts_per_page FROM ".TABLE_PREFIX."mod_news_settings WHERE section_id = ".$section_id);

    if(!is_null($posts_per_page))
    {
        $setting_posts_per_page = $posts_per_page;
    } 
	else 
	{
        $setting_posts_per_page = 0;
    }

    // Get total number of posts
    $aTempNews = [];
    $database->execute_query(
        "SELECT post_id, section_id FROM ".TABLE_PREFIX."mod_news_posts
            WHERE section_id = ".$section_id." AND active = 1 AND title != '' ".$query_extra."
            AND (published_when = 0 OR published_when <= ".$current_time.") AND (published_until = 0 OR published_until >= ".$current_time.")",
        true,
        $aTempNews,
        true
    );
    $total_num = count($aTempNews);

    // Work-out if we need to add limit code to sql
    if ($setting_posts_per_page != 0)
    {
        $limit_sql = " LIMIT ".$position.", ".$setting_posts_per_page;
    } 
	else 
	{
        $limit_sql = "";
    }

    
    $aAllPost = [];
    // hook for history preview
    // 
    if( (true === news_preview::$iUsePreview) && ($section_id == news_preview::$iPreviewID) )
    {
        // Query posts (for this page)
        $aAllPost = news_preview::$aPreviewData;
    } 
    else 
    {      
        // Query posts (for this page)
        $query_posts = $database->execute_query(
            "SELECT * FROM ".TABLE_PREFIX."mod_news_posts
                WHERE section_id = ".$section_id." AND active = 1 AND title != ''".$query_extra."
                    AND (published_when = 0 OR published_when <= ".$current_time.") AND (published_until = 0 OR published_until >= ".$current_time.")
                ORDER BY position DESC".$limit_sql,
            true,
            $aAllPost,
            true
        );
    }    
    $num_posts = count($aAllPost);

    // Create previous and next links
    $check_g = LEPTON_core::getValue("g", "integer", "get");
    if ($setting_posts_per_page != 0)
    {
        if ($position > 0)
        {
            if ($check_g !== null)
            {
                $pl_prepend = '<a href="?p='.($position - $setting_posts_per_page).'&amp;g='.$check_g.'">&lt;&lt; ';
            } else
            {
                $pl_prepend = '<a href="?p='.($position - $setting_posts_per_page).'">&lt;&lt; ';
            }

            $pl_append = '</a>';
            $previous_link = $pl_prepend.$TEXT['PREVIOUS'].$pl_append;
            $previous_page_link = $pl_prepend.$TEXT['PREVIOUS_PAGE'].$pl_append;
        } else 
		{
            $previous_link = '';
            $previous_page_link = '';
        }
		
        if($position + $setting_posts_per_page >= $total_num)
        {
            $next_link = '';
            $next_page_link = '';
        } 
		else 
		{
            if($check_g !== null)
            {
                $nl_prepend = '<a href="?p='.($position+$setting_posts_per_page).'&amp;g='.$check_g.'"> ';
            } 
			else 
			{
                $nl_prepend = '<a href="?p='.($position+$setting_posts_per_page).'"> ';
            }
			
            $nl_append = ' &gt;&gt;</a>';
            $next_link = $nl_prepend.$TEXT['NEXT'].$nl_append;
            $next_page_link = $nl_prepend.$TEXT['NEXT_PAGE'].$nl_append;
        }
		
        if($position+$setting_posts_per_page > $total_num)
        {
            $num_of = $position+$num_posts;
        } 
		else 
		{
            $num_of = $position+$setting_posts_per_page;
        }

        $out_of = ($position+1).'-'.$num_of.' '.strtolower($TEXT['OUT_OF']).' '.$total_num;
        $of = ($position+1).'-'.$num_of.' '.strtolower($TEXT['OF']).' '.$total_num;
        $display_previous_next_links = '';
    } 
	else 
	{
        $display_previous_next_links = 'none';
    }

    if ($num_posts === 0)
    {
        $setting_header = '';
        $setting_post_loop = '';
        $setting_footer = '';
        $setting_posts_per_page = '';
    }

    // Print header    
    $header_vars = [
        'NEXT_PAGE_LINK'     => (($display_previous_next_links == 'none') ? '' : $next_page_link),
        'NEXT_LINK'          => (($display_previous_next_links == 'none') ? '' : $next_link),
        'PREVIOUS_PAGE_LINK' => (($display_previous_next_links == 'none') ? '' : $previous_page_link),
        'PREVIOUS_LINK'      => (($display_previous_next_links == 'none') ? '' : $previous_link),
        'OUT_OF'             => (($display_previous_next_links == 'none') ? '' : $out_of),
        'OF'                 => (($display_previous_next_links == 'none') ? '' : $of),
        'DISPLAY_PREVIOUS_NEXT_LINKS' => $display_previous_next_links,
        'PAGE_TITLE'         => PAGE_TITLE
    ];

    $check_g = LEPTON_core::getValue("g", "integer", "get");
    $header_vars['group_info'] = ($query_extra != '')
        ? [ 'display'  => true, 'title' => ( $groups[$check_g]['title'] ?? "*"),'href'  => strip_tags($_SERVER['SCRIPT_NAME']) ]
        : [ 'display'  => false, 'title' => "", 'href'  => "" ]
        ;
    
    echo $oTWIG->render(
        "@news/header.lte",
        $header_vars
    );
    
    if ($num_posts > 0)
    {
        $vars = ['PICTURE', 'PIC_URL', 'PAGE_TITLE', 'POST_ID', 'GROUP_ID', 'GROUP_TITLE', 'GROUP_IMAGE', 'DISPLAY_GROUP', 'DISPLAY_IMAGE', 'TITLE',
                 'SHORT', 'LONG', 'LINK', 'MODI_DATE', 'MODI_TIME', 'CREATED_DATE', 'CREATED_TIME', 'PUBLISHED_DATE', 'PUBLISHED_TIME', 'USER_ID',
                 'USERNAME', 'DISPLAY_NAME', 'EMAIL', 'TEXT_READ_MORE','SHOW_READ_MORE', 'COM_COUNT'];

        foreach ($aAllPost as $post)
        {
            if (isset($groups[$post['group_id']]['active']) && $groups[$post['group_id']]['active'] != false)
            {
                // Make sure parent group is active
                $uid = $post['posted_by']; // User who last modified the post
                
                // Workout date and time of last modified post
                if ($post['published_when'] === '0')
                {
                    $post['published_when'] = time();
                }
                
                if ($post['published_when'] > $post['posted_when'])
                {
                    $post_date = date(DATE_FORMAT, $post['published_when']);
                    $post_time = date(TIME_FORMAT, $post['published_when']);
                } else {
                    $post_date = date(DATE_FORMAT, $post['posted_when']);
                    $post_time = date(TIME_FORMAT, $post['posted_when']);
                }

                $publ_date = date(DATE_FORMAT,$post['published_when']);
                $publ_time = date(TIME_FORMAT,$post['published_when']);

                // Work-out the post link
                if(DEFAULT_LANGUAGE != LANGUAGE ) 
				{				
                    //$post_link = page_link($post['link']).'?lang='.LANGUAGE;
					$post_link = LEPTON_URL . PAGES_DIRECTORY . $post['link'] . PAGE_EXTENSION.'?lang='.LANGUAGE;
                } 
				else 
				{
					//$post_link = page_link($post['link']);
					$post_link = LEPTON_URL . PAGES_DIRECTORY . $post['link'] . PAGE_EXTENSION;
                }

                $post_link_path = str_replace(LEPTON_URL, LEPTON_PATH,$post_link);
                if(file_exists($post_link_path))
                {
                    $create_date = date(DATE_FORMAT, filemtime ( $post_link_path ));
                    $create_time = date(TIME_FORMAT, filemtime ( $post_link_path ));
                } else {
                    $create_date = $publ_date;
                    $create_time = $publ_time;
                }

                $check_p = LEPTON_core::getValue('p','integer' ,'get', default: 0);
                if (($check_p > 0) AND ($position > 0))
                {
                    $post_link .= '?p='.$position;
                }
                $check_g = LEPTON_core::getValue("g", "integer", "get");
                if($check_g !== null)
                {
                    if (($check_p > 0) AND ($position > 0))
                    {
                        $post_link .= '&amp;'; 
                    }
                    else 
                    {
                         $post_link .= '?';
                    }
                    {
                        $post_link .= 'g='.$check_g;
                    }
                }

                // Get group id, title, and image
                $group_id = $post['group_id'];
				$post_id = $post['post_id'];
                $group_title = $groups[$group_id]['title'];
                $group_image = $groups[$group_id]['image'];
                $display_image = ($group_image == '') ? "none" : "inherit";
                $display_group = ($group_id == 0) ? 'none' : 'inherit';

                //  aldus - 2021-06-18
                news::cleanUpString( $group_title );

                if ($group_image != "") $group_image= "<img src='".$group_image."' alt='".$group_title."' title='".$group_title."' />";

                // Replace [wblink--PAGE_ID--] with real link
                $short = htmlspecialchars_decode($post['content_short']);
                $oLEPTON->preprocess($short);

                // Loop Post Image
                $post_pic_url = '';
                $post_picture = '';

                foreach (LEPTON_core::imageTypesAllowed() as $sMimeType)
                {
                    $sTempFilePath = MEDIA_DIRECTORY.'/newspics/image'.$post['post_id'].'.'.$sMimeType;
                    
                    if (file_exists(LEPTON_PATH.$sTempFilePath))
                    {
                        $post_pic_url = LEPTON_URL.$sTempFilePath;
                        $post_picture = '<img src="'.$post_pic_url.'" alt="'.$post['title'].'" title="'.$post['title'].'" class="news_loop_image" />';
                        break;
                    }
                }
               // number of comments:
               $com_count = '';
               $pid = $post['post_id'];
               $aAllComments = [];
               $database->execute_query(
                    "SELECT * FROM ".TABLE_PREFIX."mod_news_comments WHERE section_id = ".$section_id." AND post_id = ".$pid,
                    true,
                    $aAllComments,
                    true
                );

                $iNumOfComments = count($aAllComments);

               if ($iNumOfComments == 1)
               {
                  $com_count = $oNEWS->language["TEXT_COMMENT"]; // "1 Kommentar";
               }
			   
               if ($iNumOfComments > 1)
               {
                  $com_count = $iNumOfComments." ".$oNEWS->language["TEXT_COMMENTS"]; // Kommentare";
               } 

                news::cleanUpString( $post['title'] );

                // Replace vars with values
                $post_long_len = strlen($post['content_long']);
                $long = htmlspecialchars_decode($post['content_long']);
                
                if (isset($users[$uid]['username']) AND $users[$uid]['username'] != '')
                {
                    if ($post_long_len < 9)
                    {
                        $values = [$post_picture, $post_pic_url, PAGE_TITLE, $post_id, $group_id, $group_title, $group_image, $display_group, $display_image, $post['title'],
                            $short, $long, '#" onclick="javascript:void(0);return false;" style="cursor:no-drop;', $post_date, $post_time, $create_date, $create_time,
                            $publ_date, $publ_time, $uid, $users[$uid]['username'], $users[$uid]['display_name'], $users[$uid]['email'], '', 'hidden', $com_count];
                    } else {
                        $values = [$post_picture, $post_pic_url, PAGE_TITLE, $post_id, $group_id, $group_title, $group_image, $display_group, $display_image, $post['title'],
                            $short, $long, $post_link, $post_date, $post_time, $create_date, $create_time, $publ_date, $publ_time, $uid, $users[$uid]['username'],
                            $users[$uid]['display_name'], $users[$uid]['email'], $oNEWS->language['TEXT_READ_MORE'], 'visible', $com_count];
                    }
                } 
				else 
				{
                    if ($post_long_len < 9)
                    {
                        $values = [$post_picture, $post_pic_url, PAGE_TITLE, $post_id, $group_id, $group_title, $group_image, $display_group, $display_image, $post['title'],
                            $short, $long, '#" onclick="javascript:void(0);return false;" style="cursor:no-drop;', $post_date, $post_time, $create_date, $create_time,
                            $publ_date, $publ_time, '', '', '', '', '','hidden', $com_count];
                    } 
					else 
					{
                        $values = [$post_picture, $post_pic_url, PAGE_TITLE, $post_id, $group_id, $group_title, $group_image, $display_group, $display_image, $post['title'],
                            $short, $long, $post_link, $post_date, $post_time, $create_date, $create_time, $publ_date, $publ_time, '', '', '', '',
                            $oNEWS->language['TEXT_READ_MORE'],'visible', $com_count];
                    }
                }

                $temp_vars = array_combine ( $vars, $values );

                $temp_vars['post_published_when_own_format'] = $oDateUtil->formatWithMySQL('%d.%m.%Y', $post['published_when']); //$oDateUtil->toHTML( $post['published_when'] );
                $temp_vars['post_posted_when_own_format'] = $oDateUtil->formatWithMySQL('%d.%m.%Y', $post['posted_when']); //$oDateUtil->toHTML( $post['posted_when'] );
                $temp_vars['position'] = $post['position'];

				echo $oTWIG->render(
                    '@news/post_loop.lte',
                    $temp_vars
                );
                    
                
            }
        }
    }
    
    $footer_vars = [
        'NEXT_PAGE_LINK'    => (($display_previous_next_links == 'none') ? '' : $next_page_link),
        'NEXT_LINK'         => (($display_previous_next_links == 'none') ? '' : $next_link),
        'PREVIOUS_PAGE_LINK'    => (($display_previous_next_links == 'none') ? '' : $previous_page_link),
        'PREVIOUS_LINK'     => (($display_previous_next_links == 'none') ? '' : $previous_link),
        'OUT_OF'            => (($display_previous_next_links == 'none') ? '' : $out_of),
        'OF'                => (($display_previous_next_links == 'none') ? '' : $of),
        'DISPLAY_PREVIOUS_NEXT_LINKS' => $display_previous_next_links
    ]; 

    echo $oTWIG->render(
        '@news/footer.lte',
        $footer_vars
    );

}
elseif (defined('POST_ID') && is_numeric(POST_ID))
{
	// There is a POST id ... we try to display the details:
    if ( false === $oNEWS->display_details )
    {
        $oNEWS->display_details = true;
        $oNEWS->displayed_news = POST_ID;
    } 
	else 
	{
        //    exit gracefully - to avoid doubles if the module is placed on more than one section on the same page    
        return true;
    }

    // Get page info
    $aPageInfo = [];
    $database->execute_query(
        "SELECT link FROM ".TABLE_PREFIX."pages WHERE page_id = ".PAGE_ID,
        true,
        $aPageInfo,
        false
    );
    if (!empty($aPageInfo))
    {
        $page = $aPageInfo; // !

		$page_link = LEPTON_URL.PAGES_DIRECTORY.$page['link'].PAGE_EXTENSION;

        $check_p = LEPTON_core::getValue('p','integer' ,'get', default: 0);
        if (($check_p > 0) AND ($position > 0))
        {
            $page_link .= '?p='.$check_p; //'.$_GET['p'];
        }

        $check_g = LEPTON_core::getValue('g','integer' ,'get', default: -1);
        if ($check_g > -1)
        {
            if ($position > 0)
            {
                $page_link .= '&amp;';
            } else {
                $page_link .= '?';
            }
            
			$page_link .= 'g='.$check_g	; //$_GET['g'];
        }
    } 
	else 
	{
        exit($MESSAGE['PAGES_NOT_FOUND']);
    }

    // Get post info
    $current_time = time();
    $aAllPost = [];

    // hook for history preview
    if( (true === news_preview::$iUsePreview) )
    {
        // Theoretisch geht's
        $aAllPost = news_preview::$aPreviewData;

    } 
	else 
	{
        $database->execute_query(
            "SELECT * FROM ".TABLE_PREFIX."mod_news_posts WHERE post_id = ".POST_ID." AND active = 1
                AND (published_when = 0 OR published_when <= ".$current_time.") 
                AND (published_until = 0  OR published_until >= ".$current_time.")",
            true,
            $aAllPost,
            false
        );
    }
    if (!empty($aAllPost))
    {
        $post = $aAllPost;
        if( isset($groups[$post['group_id']]['active']) AND ($groups[$post['group_id']]['active'] != false) )
        { 
			// Make sure parent group is active
            $uid = $post['posted_by']; // User who last modified the post
            
			// Workout date and time of last modified post
            if ($post['published_when'] === '0') $post['published_when'] = time();
            if ($post['published_when'] > $post['posted_when'])
            {
                $post_date = date(DATE_FORMAT, $post['published_when']);
                $post_time = date(TIME_FORMAT, $post['published_when']);
            }
            else
            {
                $post_date = date(DATE_FORMAT, $post['posted_when']);
                $post_time = date(TIME_FORMAT, $post['posted_when']);
            }

            $publ_date = date(DATE_FORMAT,$post['published_when']);
            $publ_time = date(TIME_FORMAT,$post['published_when']);

            // Work-out the post link
			$post_link = LEPTON_URL . PAGES_DIRECTORY . $post['link'] . PAGE_EXTENSION;

            $post_link_path = str_replace(LEPTON_URL, LEPTON_PATH,$post_link);
			
            if(file_exists($post_link_path))
            {
                $create_date = date(DATE_FORMAT, filemtime ( $post_link_path ));
                $create_time = date(TIME_FORMAT, filemtime ( $post_link_path ));
            } 
			else 
			{
                $create_date = $publ_date;
                $create_time = $publ_time;
            }
            
            // Get group id, title, and group image
            $group_id = $post['group_id'];
            $group_title = $groups[$group_id]['title'];
            $group_image = $groups[$group_id]['image'];
            $display_image = ($group_image == '') ? "none" : "inherit";
            $display_group = ($group_id == 0) ? 'none' : 'inherit';

            news::cleanUpString( $group_title );

            if ($group_image != "") $group_image= "<img src='".$group_image."' alt='".$group_title."' title='".$group_title."' />";
            
            // Post Image
            $post_pic_url = '';
            $post_picture = '';
            
            foreach(LEPTON_core::imageTypesAllowed() as $sMimeType)
            {
                $sTempFilePath = MEDIA_DIRECTORY.'/newspics/image'.POST_ID.'.'.$sMimeType;
                if (file_exists(LEPTON_PATH.$sTempFilePath))
                {
                    $post_pic_url = LEPTON_URL.$sTempFilePath;
                    $post_picture = '<img src="'.$post_pic_url.'" alt="'.$post['title'].'" title="'.$post['title'].'" class="news_post_image" />';
                    break;
                }
            }
            $display_user = (isset($users[$uid]['username']) && $users[$uid]['username'] != '') ? true : false;

            $post_short = htmlspecialchars_decode($post['content_short']);
            $oLEPTON->preprocess($post_short);

            $post_long = ($post['content_long'] != '') ? $post['content_long'] : $post['content_short'];
            $post_long = htmlspecialchars_decode( $post_long );
            $oLEPTON->preprocess($post_long);

            news::cleanUpString( $post['title'] );

            $vars = [
                'PICTURE'       => $post_picture,
                'PIC_URL'       => $post_pic_url,
                'PAGE_TITLE'    => PAGE_TITLE,
                'GROUP_ID'      => $group_id,
                'GROUP_TITLE'   => $group_title,
                'GROUP_IMAGE'   => $group_image,
                'DISPLAY_GROUP' => $display_group,
                'DISPLAY_IMAGE' => $display_image,
                'TITLE'         => $post['title'],
                'SHORT'         => $post_short, // *
                'LONG'          => $post_long,  // *
                'BACK'          => $page_link,
                'TEXT_BACK'     => $oNEWS->language['TEXT_BACK'],
                'TEXT_LAST_CHANGED'    => $oNEWS->language['TEXT_LAST_CHANGED'],
                'MODI_DATE'     => $post_date,
                'TEXT_AT'       => $oNEWS->language['TEXT_AT'],
                'MODI_TIME'     => $post_time,
                'CREATED_DATE'  => $create_date,
                'CREATED_TIME'  => $create_time,
                'PUBLISHED_DATE'    => $publ_date,
                'PUBLISHED_TIME'    => $publ_time,
                'TEXT_POSTED_BY'    => $oNEWS->language['TEXT_POSTED_BY'],
                'TEXT_ON'       => $oNEWS->language['TEXT_ON'],
                'USER_ID'       => ( (true === $display_user) ? $uid : ""),
                'USERNAME'      => ( (true === $display_user) ? $users[$uid]['username'] : "" ),
                'DISPLAY_NAME'  => ( (true === $display_user) ? $users[$uid]['display_name'] : "" ),
                'EMAIL'         => ( (true === $display_user) ? $users[$uid]['email'] : "" ),
                'post_published_when_own_format' => $oDateUtil->formatWithMySQL('%d.%m.%Y', $post['published_when']), // 'post_published_when_own_format' => $oDateUtil->toHTML( $post['published_when'] ),
                'post_posted_when_own_format'    => $oDateUtil->formatWithMySQL('%d.%m.%Y', $post['posted_when'])	// 'post_posted_when_own_format'    => $oDateUtil->toHTML( $post['posted_when'] )			
            ];
        }
    } 
	else 
	{
        // no active sections here
        echo LEPTON_tools::display( "[1] ".$MESSAGE['FRONTEND_SORRY_NO_ACTIVE_SECTIONS'], "pre", "ui message red");
        return NULL;
    }

    // Print post header
    echo $oTWIG->render(
        "@news/post_header.lte",
        $vars
    );

    // Print post footer
    echo $oTWIG->render(
        "@news/post_footer.lte",
        $vars
    );
    
    // Show comments section if we have to
    if(($post['commenting'] == 'private' && isset($oLEPTON) && $oLEPTON->is_authenticated() == true) || $post['commenting'] == 'public')
    {
		// Comments header
        $vars = [
            'ADD_COMMENT_URL' => LEPTON_URL.'/modules/news/comment.php?post_id='.POST_ID.'&amp;section_id='.$section_id,
            'TEXT_COMMENTS'    => $oNEWS->language['TEXT_COMMENTS']
        ];

        echo $oTWIG->render(
            "@news/comments_header.lte",
            $vars
        );

        // Query for comments
        $aAllComments = [];
        $database->execute_query(
            "SELECT title, comment, commented_when, commented_by FROM ".TABLE_PREFIX."mod_news_comments
            WHERE post_id = ".POST_ID." ORDER BY commented_when ASC",
            true,
            $aAllComments,
            true
        );

        if (!empty($aAllComments))
        {
            foreach ($aAllComments as &$comment)
            {
                // Display Comments without slashes, but with new-line characters
                $comment['comment'] = nl2br(stripslashes($comment['comment']));
                $comment['title'] = stripslashes($comment['title']);

                news::cleanUpString( $comment['title'] );
                
                // Print comments loop
                $commented_date = date(DATE_FORMAT, $comment['commented_when']);
                $commented_time = date(TIME_FORMAT, $comment['commented_when']);
                $uid = $comment['commented_by'];
                
                $display_user = (isset($users[$uid]['username']) AND $users[$uid]['username'] != '') ? true : false;
                
                $vars = [
                    'TITLE'     => $comment['title'],
                    'COMMENT'   => $comment['comment'],
                    'TEXT_ON'   => $oNEWS->language['TEXT_ON'],
                    'DATE'      => $commented_date,
                    'TEXT_AT'   => $oNEWS->language['TEXT_AT'],
                    'TIME'      => $commented_time,
                    'TEXT_BY'   => $oNEWS->language['TEXT_BY'],
                    'USER_ID'   => ( true === $display_user ) ? $uid : '0',
                    'USERNAME'  => ( true === $display_user ) ? $users[$uid]['username'] : $oNEWS->language['TEXT_UNKNOWN'],
                    'DISPLAY_NAME' => ( true === $display_user ) ? $users[$uid]['display_name'] : $oNEWS->language['TEXT_UNKNOWN'],
                    'EMAIL'     => ( true === $display_user ) ? $users[$uid]['email'] : "",
                    'commented_when_own_format' => $oDateUtil->formatWithMySQL('%d.%m.%Y', $comment['commented_when'])	//$oDateUtil->toHTML( $comment['commented_when'] )
                ];
                
                echo $oTWIG->render(
                    '@news/comments_loop.lte',
                    $vars
                );
            }
        } 
		else 
		{
			// No comments found
            echo (isset($oNEWS->language['TEXT_NO_COMMENT'])) ? $oNEWS->language['TEXT_NO_COMMENT'].'<br />' : 'None found<br />';
        }

		// Print comments footer
        $vars = [
            'ADD_COMMENT_URL'   => LEPTON_URL.'/modules/news/comment.php?post_id='.POST_ID.'&amp;section_id='.$section_id,
            'TEXT_ADD_COMMENT'  => $oNEWS->language['TEXT_ADD_COMMENT']
        ];
        
        echo $oTWIG->render(
            "@news/comments_footer.lte",
            $vars
        );

    }

    if (ENABLED_ASP)
    {
        $_SESSION['comes_from_view'] = POST_ID;
        $_SESSION['comes_from_view_time'] = time();
    }
}
