<?php

/**
 * This file is part of LEPTON Core, released under the GNU GPL
 * Please see LICENSE and COPYING files in your package for details, specially for terms and warranties.
 * 
 * NOTICE:LEPTON CMS Package has several different licenses.
 * Please see the individual license in the header of each single file or info.php of modules and templates.
 *
 * @author          LEPTON Project
 * @copyright       2010-2026 LEPTON Project
 * @link            https://lepton-cms.org
 * @license         https://gnu.org/licenses/gpl.html
 * @license_terms   please see LICENSE and COPYING files in your package
 *
 */

// 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


/**
 *    Generates a page-tree (array) by given parameters (see below).
 *
 *    @param    int     $root_id        Any root-(page) id. Default = 0.
 *    @param    array   $page_storage   Storage-Array for the results. Pass by reference!
 *    @param    array   $fields         A linear list of field-names to collect. As default
 *                                      'page_id', 'page_title', 'menu_title', 'parent','position','visibility', 'admin_groups' are
 *                                      collected in the result-array.
 *                    Keep in mind that also 'subpages' is generated!
 *
 *    @return    void    As the storage is called by reference.
 *
 */
function page_tree(
    int $root_id = 0,
    array &$page_storage = [],
    array $fields = ['page_id', 'page_title', 'menu_title', 'parent','position', 'visibility', 'admin_groups']
    ): void
{
    global $LEPTON_CORE_all_pages;
    $database = LEPTON_database::getInstance();
    
    // [1.0.2]
    $bUserHasAdminRights = LEPTON_core::userHasAdminRights();
    // [1.0.3]
    $aUserGroups = LEPTON_CORE::getValue("groups_id", "string", "session", ",");
    
    // [1.1] make sure that required fields are in list
    $aRequiredKeys = ['page_id', 'parent', 'visibility', 'admin_groups'];
    
    foreach ($aRequiredKeys as $mustBe)
    {
        if (!in_array($mustBe, $fields))
        {
            $fields[] = $mustBe;
        }
    }

    $select_fields = "`".implode("`,`", $fields)."`";
    
    $LEPTON_CORE_all_pages = [];
    $database->execute_query(
        "SELECT ".$select_fields." FROM `".TABLE_PREFIX."pages` ORDER BY `parent`,`position`",
        true,
        $LEPTON_CORE_all_pages
    );

    // [2.1]
    foreach ($LEPTON_CORE_all_pages as &$ref)
    {
        $ref['admin_groups'] = explode(",", $ref['admin_groups']);
    }

    // [2.2]
    if ($bUserHasAdminRights == true)
    {
        foreach ($LEPTON_CORE_all_pages as &$ref)
        {
            $ref['userAllowed'] = true;
        }
    }
    else
    {
        foreach ($LEPTON_CORE_all_pages as &$ref)
        {
            $ref['userAllowed'] = !empty(array_intersect($aUserGroups, $ref['admin_groups']));
        }
    }
    
    if (in_array("viewing_groups", $fields))
    {
        foreach ($LEPTON_CORE_all_pages as &$ref)
        {
            $ref['viewing_groups'] = explode(",", $ref['viewing_groups']);
        }
    }

    LEPTON_CORE_make_list( $root_id, $page_storage );
 }
 
/**
 *    Internal Sub-function for "page_tree" to build the page-tree via recursive calls.
 *
 *    @param    int     $aNum Root-Id
 *    @param    array   $aRefArray Result-Storage. Call by reference!
 *
 */ 
function LEPTON_CORE_make_list(int $aNum, array &$aRefArray ): void
{
    global $LEPTON_CORE_all_pages, $TEXT;
    
    foreach($LEPTON_CORE_all_pages as &$ref) {
        
        if ($ref['parent'] > $aNum)
        {
            break;
        }
        
        if ($ref['parent'] == $aNum)
        {
            
            switch( $ref['visibility'] )
            {

                case 'public':
                    $ref['status_icon'] = "visible_16.png";
                    $ref['status_text'] = $TEXT['PUBLIC'];
                    $ref['status_uiicon'] = 'unhide';
                    break;

                case 'private':
                    $ref['status_icon'] = "private_16.png";
                    $ref['status_text'] = $TEXT['PRIVATE'];
                    $ref['status_uiicon'] = 'user';
                    break;

                case 'registered':
                    $ref['status_icon'] = "keys_16.png";
                    $ref['status_text'] = $TEXT['REGISTERED'];
                    $ref['status_uiicon'] = 'sign in';
                    break;

                case 'hidden':
                    $ref['status_icon'] = "hidden_16.png";
                    $ref['status_text'] = $TEXT['HIDDEN'];
                    $ref['status_uiicon'] = 'hide';
                    break;

                case 'none':
                    $ref['status_icon'] = "none_16.png";
                    $ref['status_text'] = $TEXT['NONE'];
                    $ref['status_uiicon'] = 'lock';
                    break;

                case 'deleted':
                    $ref['status_icon'] = "deleted_16.png";
                    $ref['status_text'] = $TEXT['DELETED'];
                    $ref['status_uiicon'] = 'recycle red';
                    break;

                default:
                    die(LEPTON_tools::display("Error: [20012] ".$ref['visibility']. " unknown!", "pre", "ui message red"));
                    break;

            }

            $ref['subpages'] = [];
            LEPTON_CORE_make_list( $ref['page_id'], $ref['subpages'] );

            if (isset($ref['link']))
            {
                $ref['link'] = PAGES_DIRECTORY.$ref['link'].PAGE_EXTENSION; // show link also in overview, therefore no additional LEPTON_URL
            }

            $aRefArray[] = &$ref;
        }
    }
}