<?php

/**
 * This file is part of LEPTON Core, released under the GNU GPL
 *
 * @function		get_page_footers
 * @author          LEPTON Project
 * @copyright       2010-2022 LEPTON Project
 * @link            https://lepton-cms.org
 * @license         http://www.gnu.org/licenses/gpl.html
 * @license_terms   please see LICENSE and COPYING files in your package
 *
 */

// include class.secure.php to protect this file and the whole CMS!
if(!defined("SEC_FILE")){define("SEC_FILE",'/framework/class.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("[ %s ] Can't include class.secure.php!", $_SERVER['SCRIPT_NAME']), E_USER_ERROR);
	}
}
// end include class.secure.php


/**
 * get additions for page footer (js, script)
 *
 * + gets all active sections for a page;
 * + scans module directories for file footers.inc.php;
 * + includes that file if it is available
 * @access public
 * @param  string  $for - 'frontend' (default) / 'backend'
 * @return void (echo's result)
 *
 **/
 
function get_page_footers( $for = 'frontend' )
{
	$oLEPTON = LEPTON_frontend::getInstance();
	global $FOOTERS;

	// don't do this twice
	if ( defined( 'LEP_FOOTERS_SENT' ) )
	{
		return false;
	}
	
	//  Temp. additional infostring
	$sAdditionalInfo = "";
	
	//  Initialize var with an empty string.
	$module = '';
	
	if ( !$for || $for == '' || ( $for != 'frontend' && $for != 'backend' ) )
	{
		$for = 'frontend';
	}
    // Aldus: 2021-07-16 L* 5.3
	$page_id = LEPTON_request::getPageID();
	
	if ($page_id === NULL)
	{
	    $page_id = -1; //
	}
	
	$js_subdirs = array();
	// it's an admin tool...
	$sMyTool = filter_input(INPUT_GET,'tool',FILTER_SANITIZE_SPECIAL_CHARS) ?? '';	
	if ( $for == 'backend' && isset($sMyTool) && file_exists(LEPTON_PATH.'/modules/'.$sMyTool.'/tool.php'))
	{
		$js_subdirs[] = array(
			'modules/' .$sMyTool. '/js',
			'modules/' .$sMyTool
		);
		if ( file_exists( LEPTON_PATH . '/modules/' .$sMyTool. '/footers.inc.php' ) )
		{
			addItems( $for, LEPTON_PATH . '/modules/' .$sMyTool, true );
		}
	}
	elseif ( $page_id && is_numeric( $page_id ) )
	{		
		$sections = get_active_sections( $page_id, NULL, ($for === "backend") );
		if ( is_array( $sections ) && count( $sections ) )
		{
			global $current_section;
			
			// avoid loading modules twice!
			$loaded_modules = array();
			
			foreach ( $sections as $section )
			{
				
				$module = $section[ 'module' ];
				
				if(in_array( $module, $loaded_modules))
				{
					continue;
				}
				$loaded_modules[] = $module;
				
				// find header definition file
				if ( file_exists( LEPTON_PATH . '/modules/' . $module . '/footers.inc.php' ) )
				{
					$current_section = $section[ 'section_id' ];
					addItems( $for, LEPTON_PATH . '/modules/' . $module , true);
					
				} else {
				
					$current_template = (isset($oLEPTON->page['template']) && ($oLEPTON->page['template'] != '')) ? $oLEPTON->page['template'] : DEFAULT_TEMPLATE;
					
					if ( file_exists( LEPTON_PATH . '/templates/' . $current_template . '/footers.inc.php' ) ){
						$current_section = $section[ 'section_id' ];
						addItems( $for, LEPTON_PATH . '/templates/' . $current_template , true);					
						
					}
				}
				
				$temp_js = array(
					'modules/' . $module,
					'modules/' . $module . '/js' 
				);
				
				if ( $for == 'frontend' )
				{
					$current_template = (isset($oLEPTON->page['template']) && ($oLEPTON->page['template'] != '')) ? $oLEPTON->page['template'] : DEFAULT_TEMPLATE;
					$lookup_file = "templates/".$current_template."/frontend/".$module;
					
					$temp_js[] = $lookup_file;
					$temp_js[] = $lookup_file."/js";
			
				} // end $for == 'frontend' 
				else {
					// start $for == 'backend' 
					$current_theme = DEFAULT_THEME;
					$lookup_file = "templates/".$current_theme."/backend/".$module;
					
					$temp_js[] = $lookup_file;
					$temp_js[] = $lookup_file."/js";
					
					// end $for == 'backend' 
				}
				
				$js_subdirs[]= array_reverse($temp_js);
			}
		}
		// add css/js search subdirs for frontend only; page based CSS/JS
		// does not make sense in BE
		if ( $for == 'frontend' )
		{
			$js_subdirs[] = array(
				PAGES_DIRECTORY,
				PAGES_DIRECTORY . '/js'
			);
		}
	}
	else
	{
		// load footers if no page_id exists (/account)
		$sAdditionalInfo .= "\n<!-- no page_id, no modules -->\n";
		// [3.1] Make sure that the correct template footers.inc.php is loaded
		// [3.1.0] is it the search result page?
		$sTempPagePath = filter_input(INPUT_SERVER, "REQUEST_URI", FILTER_SANITIZE_FULL_SPECIAL_CHARS);
		if(strpos($sTempPagePath, "frontend_result") !== false)
		{
		    $sAdditionalInfo .= "\n<!-- search results -->\n";
		    
		    // [3.1.1] Get the templatename from the db-table "search"
		    $sTempTemplateName = LEPTON_database::getInstance()->get_one("SELECT `value` FROM `".TABLE_PREFIX."search` where `name`='template'");
		    
		    // [3.1.2] Temp path
		    $sTempLookUp = LEPTON_PATH."/templates/".$sTempTemplateName."/footers.inc.php";
		    if(file_exists($sTempLookUp))
		    {
		        // 3.1.3 require the file
		        addItems( $for, LEPTON_PATH . '/templates/' . $sTempTemplateName , true);	
		    }
		}
		else 
		{
		    // [3.2.0] WHAT ist it? Frontend account?
		    
		    // [3.3.0] We try to get the default template footers.imc.php
		    $sAdditionalInfo .= "\n<!-- default frontend template -->\n";
		    
		    // [3.3.1] Temp path
		    $sTempLookUp = LEPTON_PATH."/templates/".DEFAULT_TEMPLATE."/footers.inc.php";
		    if(file_exists($sTempLookUp))
		    {
		        // 3.3.2 require the file
		        addItems( $for, LEPTON_PATH . '/templates/' . DEFAULT_TEMPLATE , true);	
		    }
		} 
	}	
	
	// add template JS
	// note: defined() is just to avoid warnings, the NULL does not really
	// make sense!
	if ( $for == 'backend' )
	{ 
		$subdir = ( defined( 'DEFAULT_THEME' ) ? DEFAULT_THEME : NULL );
	} else { 
		$subdir = ( defined( 'TEMPLATE' ) ? TEMPLATE : NULL );
	}
	
	if(($module != '') && (!isset($loaded_modules)))
	{ 
        $js_subdirs[0][] = 'templates/' . $subdir . '/backend/'.$module;
        $js_subdirs[0][] = 'templates/' . $subdir . '/backend/'.$module.'/js';
        $js_subdirs[0]= array_reverse($js_subdirs[0]);   
	}
	
	$js_subdirs[] = array(
        'templates/' . $subdir . '/js', 
        'templates/' . $subdir
	);
    
	// automatically add JS files
	foreach ( $js_subdirs as $first_level_dir )
	{
		foreach($first_level_dir as $directory)
		{
            $file = $directory . '/' . $for . '_body.js';
				
            if ( file_exists( LEPTON_PATH . '/' . $file ) )
            {
                $FOOTERS[ $for ][ 'js' ][] = $file;
                break;
			}
		}
	}
	
	$output = '';

    foreach ( $FOOTERS[ $for ][ 'js'] as $arr )
    {
        $output .= '<script src="' . LEPTON_URL . '/' . $arr . '"></script>' . "\n";
    }
	
	define( 'LEP_FOOTERS_SENT', true );
	
	$sAdditionalInfo .= "\n<!-- get_page_footer - ".$for."-->\n";
	
	if ( $for =='frontend') 
	{
		echo $sAdditionalInfo.$output;
	
	} 
	else 
	{
		return $sAdditionalInfo.$output;
	}
}
?>