<?php

/*  Alternate WebKit
(C) 2011-2015 by Alternate Tools
-----------------------------------------------------

File:         mod_site.php
Description:  Functions for the site area

*/

    include "mod_config.php";
    include "class_count.php";
    include "class_page.php";
    include "class_pagelist.php";
    include "class_gallery.php";
    include "class_form.php";
    include "class_theme.php";
    include "class_translation.php";
    include "class_guestbookentrylist.php";
    include "class_mail.php";
    include "class_textfile.php";

    // functions
    
    // Fille the main page with replaces
    function build_page($themeId, $pageId, $withNavigation = true, $withBackLink = true, $naviLevelOverride = "")
    {
        global $SITE_MAIN_SITE;
        global $PAGES_FOLDER;
        global $THEME_FOLDER;
        
        global $THMREP_FILE_NAVIGATION;
        global $THMREP_FILE_FOOTER;
        global $THMREP_BODY_BACKLINK;

        $pagPage = new cPage;
        $pagPage->SetFolder(retrieve_absolute_path($PAGES_FOLDER));
        $thmTheme = new cTheme;
        $thmTheme->SetFolder(retrieve_absolute_path($THEME_FOLDER));
        if (($pageId != false && $pagPage->LoadPageFromId($pageId) == false) || $thmTheme->LoadThemeFromId($themeId) == false)
        {
            print_error_message("This page cannot be displayed. Internal error!");
            return;
        }
        
        // Check, if page has a specific theme file...
        $themeFile = $thmTheme->GetCompleteFolder() . $pagPage->GetThemeFile();
        if ($pagPage->GetThemeFile() == "" || file_exists($themeFile) == false)
            $themeFile = $thmTheme->GetCompleteFolder() . $thmTheme->GetMainFile();
        $contPage = file_get_contents($themeFile);
//        $contPage = file_get_contents($thmTheme->GetCompleteFolder() . $thmTheme->GetMainFile());

        // 1. Include footer into page, cause a navigation might be in there...
        $contFooter = file_get_contents($thmTheme->GetCompleteFolder() . $thmTheme->GetFooterFile());
        $contPage = str_replace($THMREP_FILE_FOOTER, $contFooter, $contPage);

        // 2. Include navigation into page
        if ($naviLevelOverride == "")
            $showLevels = $pagPage->GetNavigationShowLevel();
        else
            $showLevels = $naviLevelOverride;
        $navLevels = get_navigation_levels($themeId);
        $navEntries = get_navigation_entries($themeId, $showLevels);
        $contNavigation = "";
        for ($i = 0; $i < count($navLevels); $i ++)
        {
            $contNavigation = "";
            if ($withNavigation == false)
            {
                $contPage = str_replace(sprintf($THMREP_FILE_NAVIGATION, $i), $contNavigation, $contPage);
            }
            else
            {
                if ($navEntries[$i] == "")  // Is this navigation level is not wanted for this page?
                    $contPage = str_replace(sprintf($THMREP_FILE_NAVIGATION, $i), $contNavigation, $contPage);
                else  // It is wanted for this page...
                    $contPage = str_replace(sprintf($THMREP_FILE_NAVIGATION, $i), build_navigation($i, $navLevels[$i], $navEntries[$i], $pageId), $contPage);
            }
        }

        // 3. Do the head parameter replacements
        $contPage = fill_head_parameters($contPage);
        
        // 4. Backlink
        if ($withBackLink == true)
            $contBackLink = $SITE_MAIN_SITE;
        else
            $contBackLink = "";
        $contPage = str_replace($THMREP_BODY_BACKLINK, $contBackLink, $contPage);

        // 5. Some additional stuff
        $contAuthor = "";
        $contModified = date("Y-m-d H:i:s");
        if ($pageId != false)
        {
            $contAuthor = $pagPage->GetAuthor();
            $contModified = $pagPage->GetModified();
        }
        $contPage = fill_site_parameters($contPage, $contAuthor, $contModified);
        
        return $contPage;
    }

    // Retrieve array of navigation levels
    function get_navigation_levels($themeId)
    {
        global $THEME_FOLDER;
        global $THMREP_FILE_SPLIT;

        $thmTheme = new cTheme;
        $thmTheme->SetFolder(retrieve_absolute_path($THEME_FOLDER));
        $thmTheme->LoadThemeFromId($themeId);

        $contNav = file_get_contents($thmTheme->GetCompleteFolder() . $thmTheme->GetNavigationFile());

        $navLevels = explode($THMREP_FILE_SPLIT, $contNav);
        
        return $navLevels;
    }
    
    // Retrieve array of navigation entries
    function get_navigation_entries($themeId, $showLevels)
    {
        global $THEME_FOLDER;
        global $THMREP_FILE_SPLIT;

        $thmTheme = new cTheme;
        $thmTheme->SetFolder(retrieve_absolute_path($THEME_FOLDER));
        $thmTheme->LoadThemeFromId($themeId);

        $contNavEntry = file_get_contents($thmTheme->GetCompleteFolder() . $thmTheme->GetNavigationEntryFile());

        $navEntries = explode($THMREP_FILE_SPLIT, $contNavEntry);
        if ($showLevels != "") // Not all levels?
        {
            $levels = explode(';', $showLevels);
            for ($i = 0; $i < count ($navEntries); $i ++)
            {
                if (in_array($i, $levels) == false)
                    $navEntries[$i] = "";  // Not found, empty it
            }
        }

        return $navEntries;
    }
    
    // Build the navigation replacement by level, navigation and entry container
    function build_navigation($navLevel, $navContainer, $navEntryContainer, $pageId)
    {
        global $SITE_MAIN_SITE;
        global $PAGES_FOLDER;
        global $THMREP_BODY_NAVIGATION_LINK;
        global $THMREP_BODY_NAVIGATION_TEXT;
        global $THMREP_FILE_NAVIGATION_ENTRY;
        global $THMREP_FILE_NAVIGATION_ENTRY_SPLIT;

        $pageList = new cPageList;
        $page = new cPage;
        $pageList->SetFolder(retrieve_absolute_path($PAGES_FOLDER));
        $page->SetFolder(retrieve_absolute_path($PAGES_FOLDER));
        $pageList->LoadPageList(1); // Nnlocked
        $pageList->SortPageList(4); // Nav pos
        $listOfPages = $pageList->GetPageList();
		$firstPage = -1;
		$lastPage = -1;
        $contOutput = "";
        $contTempEntry = "";

		// Split container into sub-containers
		// (0 = normal, 1 = active, 2 = first, 3 = last, 4 = active first, 5 = active last, >6 = individual type :)
        $navEntryContainers = explode($THMREP_FILE_NAVIGATION_ENTRY_SPLIT, $navEntryContainer);
		for ($i = 1; $i <= 5; $i ++)  // Fill with default values, if not existing...
		{
	        if (count($navEntryContainers) == $i)  // Not found?
	        {
				if ($i < 4) // First, last
			    	$navEntryContainers[$i] = $navEntryContainers[0];  // Set to normal value then...
				else   // Active first, last
			    	$navEntryContainers[$i] = $navEntryContainers[1];  // Set to active value then...
			}
		}

		// Determine first and last page....
		for ($i = 0; $i < count($listOfPages); $i ++)
        {
            $page->LoadPageFromId($listOfPages[$i]);
            if ($page->ShowInNavigation() == true && $page->GetNavigationLevel() == $navLevel)
            {
				if ($firstPage == -1)
					$firstPage = $i;
				$lastPage = $i;
			}
		}
		
		// Fill the navigation contents...
        for ($i = 0; $i < count($listOfPages); $i ++)
        {
            $page->LoadPageFromId($listOfPages[$i]);
            if ($page->ShowInNavigation() == true && $page->GetNavigationLevel() == $navLevel)
            {
            	// Build temp entry, add before and after values...
            	if ($page->GetId() == $pageId)  // Is this the current page, then use active entry...
			 	{
					if ($page->GetNavigationTitleActive() != "" || isset($navEntryContainers[$page->GetNavigationTitleActive()]) == true)
				    	$contTempEntry = $navEntryContainers[$page->GetNavigationTitleActive()];
					else
					{
						if ($i == $firstPage)
                	    	$contTempEntry = $navEntryContainers[4];
						else if ($i == $lastPage)
                	    	$contTempEntry = $navEntryContainers[5];
						else
                	    	$contTempEntry = $navEntryContainers[1];
					}
				}
				else  // Non active page
				{
					if ($page->GetNavigationTitleNormal() != "" && isset($navEntryContainers[$page->GetNavigationTitleNormal()]) == true)
                	    $contTempEntry = $navEntryContainers[$page->GetNavigationTitleNormal()];
					else
					{
						if ($i == $firstPage)
                	    	$contTempEntry = $navEntryContainers[2];
						else if ($i == $lastPage)
                	    	$contTempEntry = $navEntryContainers[3];
						else
                	    	$contTempEntry = $navEntryContainers[0];
					}
				}
				if ($page->GetType() == PAGETYPE_LINK)
                {
                    $linkUrl = $page->GetLink();
                    if (stristr($linkUrl, $SITE_MAIN_SITE) != false)
                        $linkUrl = $linkUrl . '&nav_levels=' .  $page->GetNavigationShowLevel();
                    $contTempEntry = str_replace($THMREP_BODY_NAVIGATION_LINK , $linkUrl, $contTempEntry);
                }
                else
                    $contTempEntry = str_replace($THMREP_BODY_NAVIGATION_LINK , $SITE_MAIN_SITE . '?page=' . $page->GetId(), $contTempEntry);
                $contTempEntry = str_replace($THMREP_BODY_NAVIGATION_TEXT , $page->GetNavigationTitle(), $contTempEntry);
                $contOutput = $contOutput . $contTempEntry;
            }
        }
        return str_replace(sprintf($THMREP_FILE_NAVIGATION_ENTRY, $navLevel), $contOutput, $navContainer);
    }
    
    // Insert site counter
    function build_site_counter()
    {
       global $SITE_SHOWCOUNTER;
       global $SITE_COUNTER_FILE;
       global $SITE_LOG_FILE;
       global $SITE_IP_FILE;
       global $ADMIN_LOG_ARCHIVE;
       global $MAX_LOG_SIZE;

	   $count = new class_counter;
       $count->set_files($SITE_COUNTER_FILE, $SITE_LOG_FILE, $SITE_IP_FILE, $ADMIN_LOG_ARCHIVE);
	   $count->set_max_logsize($MAX_LOG_SIZE);
	   $count->increase("A new visitor");
	   if ($SITE_SHOWCOUNTER == "1")
           return '<br><br><p class="site_counter" align="center"><b> - ' . $count->current_count_m . ' - </b></p>';

       return "";
    }
    
    // Build the sites content
    function build_site_content($contentPosition, $mainContent, $additionalContent)
    {
        global $ALIGN_TOP;
        global $ALIGN_BOTTOM;
        global $ALIGN_LEFT;
        global $ALIGN_RIGHT;
        
        $sContent = "";
        if ($contentPosition == $ALIGN_TOP || $contentPosition == "")
            $sContent = $mainContent . $additionalContent;
        else if ($contentPosition == $ALIGN_BOTTOM)
            $sContent = $additionalContent . $mainContent;
        else if ($contentPosition == $ALIGN_LEFT)
        {
            $sContent .= echo_sr('<table class="contmain_tbl" border="0">');
            $sContent .= echo_sr('  <tr class="contmain_tbl_tbltr">');
            $sContent .= echo_sr('    <td class="contmain_tbl_tbltdleft">');
            $sContent .= echo_sr($mainContent);
            $sContent .= echo_sr('    </td>');
            $sContent .= echo_sr('    <td class="contmain_tbl_tbltdright">');
            $sContent .= echo_sr($additionalContent);
            $sContent .= echo_sr('    </td>');
            $sContent .= echo_sr('  </tr>');
            $sContent .= echo_sr('</table>');
        }
        else if ($contentPosition == $ALIGN_RIGHT)
        {
            $sContent .= echo_sr('<table class="contmain_tbl" border="0">');
            $sContent .= echo_sr('  <tr class="contmain_tbl_tbltr">');
            $sContent .= echo_sr('    <td class="contmain_tbl_tbltdleft">');
            $sContent .= echo_sr($additionalContent);
            $sContent .= echo_sr('    </td>');
            $sContent .= echo_sr('    <td class="contmain_tbl_tbltdright">');
            $sContent .= echo_sr($mainContent);
            $sContent .= echo_sr('    </td>');
            $sContent .= echo_sr('  </tr>');
            $sContent .= echo_sr('</table>');
        }

        return $sContent;
    }

    // Insert the contact form
    function build_site_contact($naviLevelsOverride = false, $textAlign)
    {
        global $FORM_DEFTEXTALIGN, $ALIGN_TOP, $LINE_FEED, $SITE_FORMSECURITY;
        $sContent = "";
        $tableDescriptions = array();
        $tableValues = array();
        $tableColumns = 2;
        if ($textAlign == "")
            $textAlign = $FORM_DEFTEXTALIGN;
        if ($textAlign == $ALIGN_TOP)
            $tableColumns = 1;

        $tableDescriptions[] = get_translation('site_contact_name') . ':';
        if (isset($_POST['contact_name']) == false)
            $_POST['contact_name'] = "";
        $tableValues[] = '<input class="contact_name" type="text" name="contact_name" value="' . $_POST['contact_name'] . '">';
        $tableDescriptions[] = get_translation('site_contact_email') . ':';
        if (isset($_POST['contact_email']) == false)
            $_POST['contact_email'] = "";
        $tableValues[] = '<input class="contact_email" type="text" name="contact_email" value="' . $_POST['contact_email'] . '">';
        $tableDescriptions[] = get_translation('site_contact_message') . ':';
        if (isset($_POST['contact_message']) == false)
            $_POST['contact_message'] = "";
        $tableValues[] = '<textarea class="contact_message" name="contact_message" cols="50" rows="8">' . $_POST['contact_message'] . '</textarea>';
		if ($SITE_FORMSECURITY == "1")
		{
            $checkVal = rand(10000, 99999);
        	$tableDescriptions[] = get_translation('site_formsec_checksum') . ': ' . $checkVal;
        	if (isset($_POST['formsec_check']) == false)
                $_POST['formsec_check'] = "";
        	$tableValues[] = '<input class="contact_check" type="text" name="formsec_check" value="' . $_POST['formsec_check'] . '">';
		}
        $sContent .= echo_sr('<form method="post" action="">');
        $sContent .= build_twolevel_table('contact', $tableDescriptions, $tableValues, $tableColumns, count($tableDescriptions));
        $sContent .= echo_sr('<br>');
		if ($SITE_FORMSECURITY == "1")
            $sContent .= echo_sr('<input type="hidden" name="formsec_checkval" value="' . $checkVal . '">');
        $sContent .= echo_sr('<input type="submit" class="contact_btn" name="contact_Send" value="' . get_translation('site_contact_send') . '">');
        $sContent .= echo_sr('<input type="hidden" name="nav_levels" value="' . $naviLevelsOverride . '">');
        $sContent .= echo_sr('</form>');
        return $sContent;
    }
    
    // Insert a custom form
    function build_site_form($formId, $naviLevelsOverride = false, $textAlign)
    {
        global $FORM_FOLDER;
        global $FORM_DEFTEXTALIGN, $ALIGN_TOP, $LINE_FEED, $SITE_FORMSECURITY;
        $sContent = "";
        $tableDescriptions = array();
        $tableValues = array();
        $tableColumns = 2;
        if ($textAlign == "")
            $textAlign = $FORM_DEFTEXTALIGN;
        if ($textAlign == $ALIGN_TOP)
            $tableColumns = 1;
        $cForm = new cForm;
        $cForm->SetFolder(retrieve_absolute_path($FORM_FOLDER));
        $cForm->LoadFormFromId($formId);

        for ($i = 0; $i < $cForm->GetMaxFields(); $i ++)
        {
            if ($cForm->GetDescription($i) == "" || (
               ($cForm->GetType($i) == FORMTYPE_RADIO || $cForm->GetType($i) == FORMTYPE_COMBOBOX) && $cForm->GetValue($i) == ""))
                continue;  // Invalid, skip...
            $tableDescriptions[] = $cForm->GetDescription($i);
            $tableValues[] = "";
            if ($cForm->GetType($i) == FORMTYPE_INPUT)
            {
                if (isset($_POST['form_input' . $i]) == false)
                    $_POST['form_input' . $i] = "";
                $tableValues[$i] .= '<input class="form_input" id="form_input' . ($i + 1) .'" type="text" name="form_input' .$i . '" value="' . $_POST['form_input' . $i] . '"';
                if ($cForm->GetSize($i) != "" && is_numeric($cForm->GetSize($i)) == true)
                    $tableValues[$i] .= ' size="' .  $cForm->GetSize($i) . '"';
                if ($cForm->GetLength($i) != "" && is_numeric($cForm->GetLength($i)) == true)
                    $tableValues[$i] .= ' maxlength="' .  $cForm->GetLength($i) . '"';
                $tableValues[$i] .= '>';
            }
            else if ($cForm->GetType($i) == FORMTYPE_TEXTINPUT)
            {
                if (isset($_POST['form_input' . $i]) == false)
                    $_POST['form_input' . $i] = "";
                $tableValues[$i] .= '<textarea class="form_textinput" id="form_textinput' . ($i + 1) .'" name="form_input' .$i . '"';
                if ($cForm->GetSize($i) != "" && is_numeric($cForm->GetSize($i)) == true)
                    $tableValues[$i] .= ' cols="' .  $cForm->GetSize($i) . '"';
                if ($cForm->GetLength($i) != "" && is_numeric($cForm->GetLength($i)) == true)
                    $tableValues[$i] .= ' rows="' .  $cForm->GetLength($i) . '"';
                $tableValues[$i] .= '>' . $_POST['form_input' . $i] . '</textarea>';
            }
            else if ($cForm->GetType($i) == FORMTYPE_COMBOBOX)
            {
                if (isset($_POST['form_input' . $i]) == false)
                    $_POST['form_input' . $i] = "";
                $tableValues[$i] .= '<select class="form_combobox" id="form_combobox' . ($i + 1) .'" name="form_input' .$i . '">' . $LINE_FEED;
                $values = explode(";", $cForm->GetValue($i));
                for ($v = 0; $v < count($values); $v ++)
                {
                    $tableValues[$i] .= '      <option value="' . $values[$v] . '"';
                    if ($_POST['form_input' . $i] == $values[$v])
                        $tableValues[$i] .= ' selected';
                    $tableValues[$i] .= '>' . $values[$v] . '</option>' . $LINE_FEED;
                }
                $tableValues[$i] .= '      </select>';
            }
            else if ($cForm->GetType($i) == FORMTYPE_RADIO)
            {
                if (isset($_POST['form_input' . $i]) == false)
                    $_POST['form_input' . $i] = "";
                $values = explode(";", $cForm->GetValue($i));
                for ($v = 0; $v < count($values); $v ++)
                {
                    $tableValues[$i] .= $LINE_FEED. '      <input type="radio" class="form_radio" id="form_radio' . ($i + 1) .'_' . ($v + 1) . '" name="form_input' .$i . '" value="' . $values[$v] . '"';
                    if ($_POST['form_input' . $i] == $values[$v])
                        $tableValues[$i] .= ' checked';
                    $tableValues[$i] .= '>' . $values[$v] . $LINE_FEED;
                }
            }
            else if ($cForm->GetType($i) == FORMTYPE_CHECKBOX)
            {
                $tableValues[$i] .= '<input class="form_checkbox" id="form_checkbox' . ($i + 1) .'" type="checkbox" name="form_input' .$i . '" value="1"';
                if (isset($_POST['form_input' . $i]) == true)
                    $tableValues[$i] .= ' checked';
                $tableValues[$i] .= '>';
            }
        }
		if ($SITE_FORMSECURITY == "1")
		{
            $checkVal = rand(10000, 99999);
        	$tableDescriptions[] = get_translation('site_formsec_checksum') . ': ' . $checkVal;
        	if (isset($_POST['formsec_check']) == false)
                $_POST['formsec_check'] = "";
        	$tableValues[] = '<input class="form_check" type="text" name="formsec_check" value="' . $_POST['formsec_check'] . '">';
		}
        $sContent .= echo_sr('<form method="post" action="">');
        $sContent .= build_twolevel_table('form', $tableDescriptions, $tableValues, $tableColumns, count($tableDescriptions));
        $sContent .= echo_sr('<br>');
		if ($SITE_FORMSECURITY == "1")
            $sContent .= echo_sr('<input type="hidden" name="formsec_checkval" value="' . $checkVal . '">');
        $sContent .= echo_sr('<input type="submit" class="form_btn" name="form_Send" value="' . get_translation('site_form_send') . '">');
        $sContent .= echo_sr('<input type="hidden" name="nav_levels" value="' . $naviLevelsOverride . '">');
        $sContent .= echo_sr('</form>');
        return $sContent;
    }

    // Insert guestbook
    function build_site_guestbook_content($pageId, $naviLevelsOverride = false, $textAlign)
    {
        global $GUESTBOOK_FOLDER;
        global $FORM_DEFTEXTALIGN, $ALIGN_TOP, $LINE_FEED;
        $sContent = "";
        $tableDescriptions = array();
        $tableValues = array();
        $tableColumns = 2;
        $idValue = 1;
        if ($textAlign == "")
            $textAlign = $FORM_DEFTEXTALIGN;
        if ($textAlign == $ALIGN_TOP)
            $tableColumns = 1;
        $guestEntry = new cGuestbookEntry;
        $guestEntry->SetFolder(retrieve_absolute_path($GUESTBOOK_FOLDER));
        $guestList = new cGuestbookEntryList;
        $guestList->SetFolder(retrieve_absolute_path($GUESTBOOK_FOLDER));
        $guestList->SetPageId($pageId);

        $sContent .= echo_sr('<br><form method="post" action="">');
        $sContent .= echo_sr('<input type="submit" class="guestbook_btn" name="guestbook_Add" value="' . get_translation('site_guestbook_addentry') . '">');
        $sContent .= echo_sr('<input type="hidden" name="nav_levels" value="' . $naviLevelsOverride . '">');
        $sContent .= echo_sr('</form>');

        $guestList->LoadGuestbookEntryList(1);  // unlocked
        $list = $guestList->GetGuestbookEntryList();
        rsort($list);

        $tableDescriptions[] = get_translation('site_guestbook_date') . ':';
        $tableValues[] = "";
        $tableDescriptions[] = get_translation('site_guestbook_title') . ':';
        $tableValues[] = "";
        $tableDescriptions[] = get_translation('site_guestbook_name') . ':';
        $tableValues[] = "";
        $tableDescriptions[] = get_translation('site_guestbook_email') . ':';
        $tableValues[] = "";
        $tableDescriptions[] = get_translation('site_guestbook_text') . ':';
        $tableValues[] = "";

        foreach ($list as $value)
        {
            $guestEntry->LoadGuestbookEntryFromId($value);
            $sContent .= echo_sr('<hr>');
            $tableValues[0] = $guestEntry->GetEnterDate();
            $tableValues[1] = $guestEntry->GetTitle();
            $tableValues[2] = $guestEntry->GetName();
            $tableValues[3] = $guestEntry->GetEmail();
            $tableValues[4] = $guestEntry->GetText();
            $sContent .= build_twolevel_table('guestbook', $tableDescriptions, $tableValues, $tableColumns, count($tableDescriptions), $idValue);
            $idValue += count($tableDescriptions);
        }
        return $sContent;
    }

    // Insert guestbook add entry
    function build_site_guestbook_add($pageId, $naviLevelsOverride = false, $textAlign)
    {
        global $FORM_DEFTEXTALIGN, $ALIGN_TOP, $LINE_FEED, $SITE_FORMSECURITY;
        $sContent = "";
        $tableDescriptions = array();
        $tableValues = array();
        $tableColumns = 2;
        if ($textAlign == "")
            $textAlign = $FORM_DEFTEXTALIGN;
        if ($textAlign == $ALIGN_TOP)
            $tableColumns = 1;

        $tableDescriptions[] = get_translation('site_guestbook_title') . ':';
        if (isset($_POST['guestbook_title']) == false)
            $_POST['guestbook_title'] = "";
        $tableValues[] = '<input class="guestbook_title" type="text" name="guestbook_title" value="' . $_POST['guestbook_title'] . '">';
        $tableDescriptions[] = get_translation('site_guestbook_name') . ':';
        if (isset($_POST['guestbook_name']) == false)
            $_POST['guestbook_name'] = "";
        $tableValues[] = '<input class="guestbook_name" type="text" name="guestbook_name" value="' . $_POST['guestbook_name'] . '">';
        $tableDescriptions[] = get_translation('site_guestbook_email') . ':';
        if (isset($_POST['guestbook_email']) == false)
            $_POST['guestbook_email'] = "";
        $tableValues[] = '<input class="guestbook_email" type="text" name="guestbook_email" value="' . $_POST['guestbook_email'] . '">';
        $tableDescriptions[] = get_translation('site_guestbook_text') . ':';
        if (isset($_POST['guestbook_text']) == false)
            $_POST['guestbook_text'] = "";
        $tableValues[] = '<textarea class="guestbook_text" cols="50" rows="8" name="guestbook_text">' . $_POST['guestbook_text'] . '</textarea>';
		if ($SITE_FORMSECURITY == "1")
		{
            $checkVal = rand(10000, 99999);
        	$tableDescriptions[] = get_translation('site_formsec_checksum') . ': ' . $checkVal;
        	if (isset($_POST['formsec_check']) == false)
                $_POST['formsec_check'] = "";
        	$tableValues[] = '<input class="guestbook_check" type="text" name="formsec_check" value="' . $_POST['formsec_check'] . '">';
		}
        $sContent .= echo_sr('<br><br>' . get_translation('site_guestbook_addentry'));
        $sContent .= echo_sr('<form method="post" action="">');
        $sContent .= build_twolevel_table('guestbook', $tableDescriptions, $tableValues, $tableColumns, count($tableDescriptions));
		if ($SITE_FORMSECURITY == "1")
            $sContent .= echo_sr('<input type="hidden" name="formsec_checkval" value="' . $checkVal . '">');
        $sContent .= echo_sr('<input type="submit" class="guestbook_btn" name="guestbook_Save" value="' . get_translation('site_guestbook_save') . '">');
        $sContent .= echo_sr('<input type="submit" class="guestbook_btn" name="guestbook_Cancel" value="' . get_translation('site_guestbook_cancel') . '">');
        $sContent .= echo_sr('<input type="hidden" name="nav_levels" value="' . $naviLevelsOverride . '">');
        $sContent .= echo_sr('</form>');
        return $sContent;
    }
    
    // Insert a gallery
    function build_site_gallery($galId, $cols, $align, $textAlign, $thumbWidth, $thumbHeight, $imgWidth, $imgHeight, $autoSize)
    {
        global $GALLERIES_FOLDER;
        global $SITE_DISPLAYPICTURE_SITE;
        global $ALIGN_TOP;
        global $GALLERYIMAGES_SIZE_AUTO;
        $galFolder = retrieve_absolute_path($GALLERIES_FOLDER);
        $galGallery = new cGallery;
        $galGallery->SetFolder($galFolder);
        $colCount = 0;
        $rowCount = 0;
        $sContent = "";
        $galImages = array();
        $galDescriptions = array();
        $colWidth = (int)(100 / $cols);

        if ($galGallery->LoadGalleryFromId($galId) == false)
            return "";

        $galGallery->SortForFrontend();
        $sContent .= echo_sr('<table border="0" width="100%" class="gallery_tbl">');
        for ($i = 0; $i < $galGallery->GetMaxImages(); $i ++)
        {
            if (file_exists(retrieve_absolute_path($galGallery->GetImage($i))) == true)
            {
                $galImages[] = retrieve_absolute_path($galGallery->GetImage($i));
                $galDescriptions[] = $galGallery->GetDescription($i);
                if ($colCount == 0)
                    $sContent .= echo_sr('  <tr class="gallery_tbltr" id="gallery_tbltr' . ($rowCount + 1) . '">');
                if ($textAlign == $ALIGN_TOP)
                {
                    $sContent .= echo_sr('    <td class="gallery_tbltd" id="gallery_tbltd' . ($rowCount + 1) . '_' . ($colCount + 1) . '" width="' . $colWidth . '%" align="' . $align . '" style="vertical-align: bottom">');
                    if ($galGallery->ShowDescriptions() == true)
                        $sContent .= echo_sr('    ' . $galGallery->GetDescription($i) . '<br>');
                }
                else
                    $sContent .= echo_sr('    <td class="gallery_tbltd" id="gallery_tbltd' . ($rowCount + 1) . '_' . ($colCount + 1) . '" width="' . $colWidth . '%" align="' . $align . '" style="vertical-align: top">');
                if ($galGallery->EnablePreview() == true)
                {
                    if ($galGallery->GetPreviewType() == GALLERY_PREVIEW_TYPE_IMAGE)
                    {
                        if ($galGallery->OpenInNewWindow() == true)
                            $sContent .= echo_s('    <a href="' . retrieve_absolute_path($galGallery->GetImage($i)) . '" target="_blank">');
                        else
                            $sContent .= echo_s('    <a href="' . retrieve_absolute_path($galGallery->GetImage($i)) . '">');
                    }
                    else if ($galGallery->GetPreviewType() == GALLERY_PREVIEW_TYPE_NEWWINDOW)
                        $sContent .= echo_sr('    <a href="JavaScript:openPreview(\'' . $SITE_DISPLAYPICTURE_SITE . '?id=' . $galId . '&amp;folder=' . $galFolder . '&amp;count=' . $i . '&align=' . $align . '&textalign=' . $textAlign . '\');">');
                    else if ($galGallery->GetPreviewType() == GALLERY_PREVIEW_TYPE_SAMEWINDOW)  // Lightbox
                        $sContent .= echo_sr('    <a href="' . retrieve_absolute_path($galGallery->GetImage($i)) . '" data-lightbox="' . $galGallery->GetId() . '" data-title="' . $galGallery->GetDescription($i) . '">');
                    else if ($galGallery->GetPreviewType() == GALLERY_PREVIEW_TYPE_SAMEWINDOW2)  // Fancybox
                        $sContent .= echo_sr('    <a href="' . retrieve_absolute_path($galGallery->GetImage($i)) . '" rel="example_group" title="' . $galGallery->GetDescription($i) . '">');
                    else if ($galGallery->GetPreviewType() == GALLERY_PREVIEW_TYPE_SAMEWINDOW3)  // DaFlashBox
                        $sContent .= echo_sr('    <a href="JavaScript:openPreview2(\'' . count($galImages) . '\');">');
                }
                else if ($galGallery->GetLink($i) != "")
                {
                    if ($galGallery->OpenInNewWindow() == true)
                        $sContent .= echo_s('    <a href="' . $galGallery->GetLink($i) . '" target="_blank">');
                    else
                        $sContent .= echo_s('    <a href="' . $galGallery->GetLink($i) . '">');
                }
                if ($autoSize == $GALLERYIMAGES_SIZE_AUTO)
                    $sContent .= echo_s('    <img src="' . retrieve_absolute_path($galGallery->GetThumb($i)) . '" class="gallery_image" id="gallery_image' . count($galImages) . '" width="' . $thumbWidth . '" height="' . $thumbHeight . '"');
                else
                    $sContent .= echo_s('    <img src="' . retrieve_absolute_path($galGallery->GetThumb($i)) . '" class="gallery_image" id="gallery_image' . count($galImages) . '"');
                if ($galGallery->ShowDescriptions() == true)
                    $sContent .= echo_s(' alt="' . $galGallery->GetDescription($i) . '" title="' . $galGallery->GetDescription($i) . '">');
                else
                    $sContent .= echo_s(' alt="" title="">');
                if ($galGallery->EnablePreview() == true || $galGallery->GetLink($i) != "")
                    $sContent .= echo_sr('</a>');
                if ($textAlign != $ALIGN_TOP && $galGallery->ShowDescriptions() == true)
                    $sContent .= echo_sr('    <br>' . $galGallery->GetDescription($i));
                $sContent .= echo_sr('    </td>');
                $colCount ++;
                if ($colCount == $cols)
                {
                    $colCount = 0;
                    $rowCount ++;
                    $sContent .= echo_sr('  </tr>');
                }
            }
        }
        $sContent .= echo_sr('</table>');
        if ($galGallery->GetPreviewType() == GALLERY_PREVIEW_TYPE_NEWWINDOW)  // JavaScript for image in new window
        {
            $sContent .= echo_sr('<script language="JavaScript" type="Text/JavaScript">');
            $sContent .= echo_sr('function openPreview(link) { ');
            $sContent .= echo_sr('  window.open(link, "", "scrollbars=yes,fullscreen"); }');
            $sContent .= echo_sr('</script>');
        }
        else if ($galGallery->GetPreviewType() == GALLERY_PREVIEW_TYPE_SAMEWINDOW3)  // DaFlashBox JavaScript :)
        {
            $sContent .= echo_sr('<script language="JavaScript" type="Text/JavaScript">');
            $sImages = "";
            $sDescriptions = "";
            for ($i = 0; $i < count($galImages); $i ++)
            {
                 $sImages = $sImages . "'" . $galImages[$i] . "'";
                 $sDescriptions = $sDescriptions . "'" . $galDescriptions[$i] . "'";
                 if ($i < count($galImages) - 1)
                 {
                     $sImages = $sImages . ", ";
                     $sDescriptions = $sDescriptions . ", ";
                 }
            }
            $sContent .= echo_sr('var gImages = new Array(' . $sImages . ');');
            $sContent .= echo_sr('var gDescriptions = new Array(' . $sDescriptions . ');');
            $sContent .= echo_sr('var gImageCount = ' . count($galImages) . ', gCurrentImage = 1;');
            $sContent .= echo_sr('function openPreview2(imageIndex) { ');
            $sContent .= echo_sr('  gCurrentImage = imageIndex;');
            $sContent .= echo_sr('  var image = document.getElementById(\'gallery2_image\');');
            $sContent .= echo_sr('  image.src = gImages[gCurrentImage - 1];');
            $sContent .= echo_sr('  showElement(document.getElementById(\'gallery2_container\'), true);');
            $sContent .= echo_sr('  showElement(document.getElementById(\'gallery2_imagecontainer\'), true);');
            if ($textAlign == $ALIGN_TOP)
            {
                if ($galGallery->ShowDescriptions() == true)
                    $sContent .= echo_sr('  document.getElementById(\'gallery2_header\').innerHTML = \'' . get_translation('site_displayimage_image') . ' \' + gCurrentImage + \' ' . get_translation('site_displayimage_of') . ' \' + gImageCount + \'<br>\' + gDescriptions[gCurrentImage - 1];');
                else
                    $sContent .= echo_sr('  document.getElementById(\'gallery2_header\').innerHTML = \'' . get_translation('site_displayimage_image') . ' \' + gCurrentImage + \' ' . get_translation('site_displayimage_of') . ' \' + gImageCount;');
            }
            else
            {
                if ($galGallery->ShowDescriptions() == true)
                    $sContent .= echo_sr('  document.getElementById(\'gallery2_footer\').innerHTML = \'' . get_translation('site_displayimage_image') . ' \' + gCurrentImage + \' ' . get_translation('site_displayimage_of') . ' \' + gImageCount + \'<br>\' + gDescriptions[gCurrentImage - 1];');
                else
                    $sContent .= echo_sr('  document.getElementById(\'gallery2_footer\').innerHTML = \'' . get_translation('site_displayimage_image') . ' \' + gCurrentImage + \' ' . get_translation('site_displayimage_of') . ' \' + gImageCount;');
            }
            $sContent .= echo_sr('  if (image.clientHeight > (getDocumentViewHeight() - 100)) image.style.height = (getDocumentViewHeight() - 100)');
            $sContent .= echo_sr('  document.getElementById(\'gallery2_imagecontainer\').style.left = getDocumentLeft();');
            $sContent .= echo_sr('  document.getElementById(\'gallery2_imagecontainer\').style.top = getDocumentTop();');
            $sContent .= echo_sr('  document.getElementById(\'gallery2_container\').style.width = getDocumentWidth();');
            $sContent .= echo_sr('  document.getElementById(\'gallery2_container\').style.height = getDocumentHeight();');
            $sContent .= echo_sr('  positionButtons();');
            $sContent .= echo_sr('  showButtons(true); }');
            $sContent .= echo_sr('function closePreview2() {');
            $sContent .= echo_sr('  showElement(document.getElementById(\'gallery2_container\'), false);');
            $sContent .= echo_sr('  showElement(document.getElementById(\'gallery2_imagecontainer\'), false);');
            $sContent .= echo_sr('  showButtons(false); }');
            $sContent .= echo_sr('function positionButtons() {');
            $sContent .= echo_sr('  var image = document.getElementById(\'gallery2_image\');');
            $sContent .= echo_sr('  var btn_last = document.getElementById(\'gallery2_btn_previous\');');
            $sContent .= echo_sr('  var btn_next = document.getElementById(\'gallery2_btn_next\');');
            $sContent .= echo_sr('  var btn_close = document.getElementById(\'gallery2_btn_close\');');
            $sContent .= echo_sr('  var rectImg  = document.getElementById(\'gallery2_image\').getBoundingClientRect();');
            $sContent .= echo_sr('  var rectSelf = btn_last.getBoundingClientRect();');
            $sContent .= echo_sr('  if (image.clientHeight > (getDocumentViewHeight() - 100)) image.style.height = (getDocumentViewHeight() - 100)');
            $sContent .= echo_sr('  btn_last.style.left = rectImg.left;');
            $sContent .= echo_sr('  btn_last.style.top = ((rectImg.bottom - rectImg.top) / 2);');
            $sContent .= echo_sr('  btn_next.style.left = rectImg.right - (rectSelf.right - rectSelf.left);');
            $sContent .= echo_sr('  btn_next.style.top = ((rectImg.bottom - rectImg.top) / 2);');
            $sContent .= echo_sr('  btn_close.style.left = rectImg.right - (rectSelf.right - rectSelf.left);');
            $sContent .= echo_sr('  btn_close.style.top = rectImg.top; }');
            $sContent .= echo_sr('function getDocumentHeight() {');
            $sContent .= echo_sr('  var body = document.body, html = document.documentElement;');
            $sContent .= echo_sr('  return Math.max( body.scrollHeight, body.offsetHeight, html.clientHeight, html.scrollHeight, html.offsetHeight ); }');
            $sContent .= echo_sr('function getDocumentWidth() {');
            $sContent .= echo_sr('  var body = document.body, html = document.documentElement;');
            $sContent .= echo_sr('  return Math.max( body.scrollWidth, body.offsetWidth, html.clientWidth, html.scrollWidth, html.offsetWidth ); }');
            $sContent .= echo_sr('function getDocumentViewHeight() {');
            $sContent .= echo_sr('  if(self.innerHeight) return window.innerHeight;');
            $sContent .= echo_sr('  else if(document.documentElement && document.documentElement.clientHeight) return document.documentElement.clientHeight;');
            $sContent .= echo_sr('  else if(document.body) return document.body.clientHeight; }');
            $sContent .= echo_sr('function getDocumentLeft() {');
            $sContent .= echo_sr('  var doc = document.documentElement;');
            $sContent .= echo_sr('  return (window.pageXOffset || doc.scrollLeft) - (doc.clientLeft || 0); }');
            $sContent .= echo_sr('function getDocumentTop() {');
            $sContent .= echo_sr('  var doc = document.documentElement;');
            $sContent .= echo_sr('  return (window.pageYOffset || doc.scrollTop)  - (doc.clientTop || 0); }');
            $sContent .= echo_sr('function showButtons(showIt) {');
            $sContent .= echo_sr('  var btn_last = document.getElementById(\'gallery2_btn_previous\');');
            $sContent .= echo_sr('  var btn_next = document.getElementById(\'gallery2_btn_next\');');
            $sContent .= echo_sr('  var btn_close = document.getElementById(\'gallery2_btn_close\');');
            $sContent .= echo_sr('  if (showIt) positionButtons();');
            $sContent .= echo_sr('  showElement(btn_last, false);');
            $sContent .= echo_sr('  if (gCurrentImage > 1) showElement(btn_last, showIt);');
            $sContent .= echo_sr('  showElement(btn_next, false);');
            $sContent .= echo_sr('  if (gCurrentImage < gImageCount) showElement(btn_next, showIt);');
            $sContent .= echo_sr('  showElement(btn_close, showIt); }');
            $sContent .= echo_sr('function showElement(element, showIt) {');
            $sContent .= echo_sr('  if (showIt == false) element.style.visibility = \'hidden\';');
            $sContent .= echo_sr('  else element.style.visibility = \'visible\'; }');
            $sContent .= echo_sr('function nextImage() {');
            $sContent .= echo_sr('  if (gCurrentImage < gImageCount) gCurrentImage ++; openPreview2(gCurrentImage); }');
            $sContent .= echo_sr('function previousImage() {');
            $sContent .= echo_sr('  if (gCurrentImage > 1) gCurrentImage --; openPreview2(gCurrentImage); }');
            $sContent .= echo_sr('</script>');
        }
        return $sContent;
    }
    function build_site_gallery_headincludes($galId, $pageContent)
    {
        global $GALLERIES_FOLDER, $IMAGE_PREVIEW2_FILE, $IMAGE_PREVIEW_FILE;
        $galFolder = retrieve_absolute_path($GALLERIES_FOLDER);
        $galGallery = new cGallery;
        $galGallery->SetFolder($galFolder);
        $sContent = "";

        if ($galGallery->LoadGalleryFromId($galId) == false || $galGallery->GetPreviewType() == GALLERY_PREVIEW_TYPE_IMAGE || $galGallery->GetPreviewType() == GALLERY_PREVIEW_TYPE_NEWWINDOW)
            return $pageContent;  // Nothing to do here...

        if ($galGallery->GetPreviewType() == GALLERY_PREVIEW_TYPE_SAMEWINDOW)  // Lightbox
        {
            $sContent .= echo_sr('<script type="text/JavaScript" src="./modules/mod_image_lightbox/js/jquery-1.11.0.min.js"></script>');
            $sContent .= echo_sr('<script type="text/JavaScript" src="' . $IMAGE_PREVIEW_FILE . '"></script>');
            $sContent .= echo_sr('<link rel=stylesheet type="text/css" href="./modules/mod_image_lightbox/css/lightbox.css">');
        }
        else if ($galGallery->GetPreviewType() == GALLERY_PREVIEW_TYPE_SAMEWINDOW2) // Fancybox
        {
            $sContent .= echo_sr('<script type="text/JavaScript" src="./modules/mod_image_fancybox/jquery-1.4.3.min.js"></script>');
            $sContent .= echo_sr('<script type="text/JavaScript" src="./modules/mod_image_fancybox/fancybox/jquery.mousewheel-3.0.4.pack.js"></script>');
            $sContent .= echo_sr('<script type="text/JavaScript" src="./modules/mod_image_fancybox/fancybox/jquery.fancybox-1.3.4.pack.js"></script>');
            $sContent .= echo_sr('<link rel="stylesheet" type="text/css" href="./modules/mod_image_fancybox/fancybox/jquery.fancybox-1.3.4.css" media="screen">');
            $sContent .= echo_sr('<script type="text/JavaScript" src="' . $IMAGE_PREVIEW2_FILE . '"></script>');
        }
        else if ($galGallery->GetPreviewType() == GALLERY_PREVIEW_TYPE_SAMEWINDOW3) // DaFlashBox :)
        {
            $sContent .= echo_sr('<div class="gallery2_container" id="gallery2_container" style="left: 0px; top: 0px; width: 100%; height: 100%; background: rgba(0, 0, 0, 0.8); position: absolute; visibility: hidden; text-align: center; z-index: 1100; overflow: auto;">');
            $sContent .= echo_sr('<div class="gallery2_imagecontainer" id="gallery2_imagecontainer" style="width: 100%; height: 100%; position: relative; visibility: hidden; text-align: center;">');
            $sContent .= echo_sr('  <div class="gallery2_btn_previous" id="gallery2_btn_previous" onMouseOver="showButtons(true);" onMouseOut="showButtons(false);" onClick="previousImage();" style="width: 40px; height: 40px; position: absolute; background-color: #FFFFFF; font-size: 30px; color: #000000; cursor: pointer;">&lt;</div>');
            $sContent .= echo_sr('  <div class="gallery2_btn_next" id="gallery2_btn_next" onMouseOver="showButtons(true);" onMouseOut="showButtons(false);" onClick="nextImage();" style="width: 40px; height: 40px; position: absolute; background-color: #FFFFFF; font-size: 30px; color: #000000; cursor: pointer;">&gt;</div>');
            $sContent .= echo_sr('  <div class="gallery2_btn_close" id="gallery2_btn_close" onMouseOver="showButtons(true);" onMouseOut="showButtons(false);" onClick="closePreview2();" style="width: 40px; height: 40px; position: absolute; background-color: #FFFFFF; font-size: 30px; color: #000000; cursor: pointer;">x</div>');
            $sContent .= echo_sr('  <div class="gallery2_header" id="gallery2_header" style="width: 100%; height: 30px; color: #ECECEC;"></div>');
            $sContent .= echo_sr('  <img class="gallery2_image" id="gallery2_image" src="" alt="" onLoad="positionButtons();" onMouseOver="showButtons(true);" onMouseOut="showButtons(false);" onDblClick="closePreview2();" style="margin: 10px; width: auto; border: 5px; border-style: solid; border-color: #FFFFFF; z-index: 1100;">');
            $sContent .= echo_sr('  <div class="gallery2_footer" id="gallery2_footer" style="width: 100%; height: 30px; color: #ECECEC;"></div>');
            $sContent .= echo_sr('</div>');
            $sContent .= echo_sr('</div>');
            return inject_into_body($sContent, $pageContent, false);  // Must be injected into body
        }
        return inject_into_head($sContent, $pageContent, false);
    }

    // Insert a youtube gallery
    function build_site_youtubegallery($galId, $cols, $align, $textAlign, $videoWidth, $videoHeight)
    {
        global $GALLERIES_FOLDER;
        global $ALIGN_TOP;
        $galFolder = retrieve_absolute_path($GALLERIES_FOLDER);
        $galGallery = new cYouTubeGallery;
        $galGallery->SetFolder($galFolder);
        $colCount = 0;
        $rowCount = 0;
        $sContent = "";
        $colWidth = (int)(100 / $cols);

        if ($galGallery->LoadYouTubeGalleryFromId($galId) == false)
            return "";

        $galGallery->SortForFrontend();
        $sContent .= echo_sr('<table border="0" width="100%" class="youtube_tbl">');
        for ($i = 0; $i < $galGallery->GetMaxYVideos(); $i ++)
        {
            if ($galGallery->GetYouTubeLink($i) != "")
            {
                if ($colCount == 0)
                    $sContent .= echo_sr('  <tr class="youtube_tbltr" id="youtube_tbltr' . ($rowCount + 1) . '">');
                if ($textAlign == $ALIGN_TOP)
                {
                    $sContent .= echo_sr('    <td class="youtube_tbltd" id="youtube_tbltd' . ($rowCount + 1) . '_' . ($colCount + 1) . '" width="' . $colWidth . '%" align="' . $align . '" style="vertical-align: bottom">');
                    if ($galGallery->ShowDescriptions() == true)
                        $sContent .= echo_sr('    ' . $galGallery->GetDescription($i) . '<br>');
                }
                else
                    $sContent .= echo_sr('    <td class="youtube_tbltd" id="youtube_tbltd' . ($rowCount + 1) . '_' . ($colCount + 1) . '" width="' . $colWidth . '%" align="' . $align . '" style="vertical-align: top">');

				$sContent .= echo_s('    <iframe class="youtube_iframe" width="' . $videoWidth . '" height="' . $videoHeight . '" src="' . $galGallery->GetYouTubeLink($i));
                if ($galGallery->ShowRelated() == false)  // No related videos?
                    $sContent .= echo_s('?rel=0');
                $sContent .= echo_sr('" frameborder="0">');
                $sContent .= echo_sr('</iframe>');
                if ($textAlign != $ALIGN_TOP && $galGallery->ShowDescriptions() == true)
                    $sContent .= echo_sr('    <br>' . $galGallery->GetDescription($i));
                $sContent .= echo_sr('    </td>');
                $colCount ++;
                if ($colCount == $cols)
                {
                    $colCount = 0;
                    $rowCount ++;
                    $sContent .= echo_sr('  </tr>');
                }
            }
        }
        $sContent .= echo_sr('</table>');

        return $sContent;
    }

    // Insert a link list
    function build_site_linklist($galId, $cols, $align, $textAlign)
    {
        global $GALLERIES_FOLDER;
        global $ALIGN_TOP;
        $galFolder = retrieve_absolute_path($GALLERIES_FOLDER);
        $lilLinkList = new cLinkList;
        $lilLinkList->SetFolder($galFolder);
        $colCount = 0;
        $rowCount = 0;
        $sContent = "";
        $colWidth = (int)(100 / $cols);

        if ($lilLinkList->LoadLinkListFromId($galId) == false)
            return "";

        $lilLinkList->SortForFrontend();
        $sContent .= echo_sr('<table border="0" width="100%" class="linklist_tbl">');
        for ($i = 0; $i < $lilLinkList->GetMaxLinks(); $i ++)
        {
            if ($lilLinkList->GetLink($i) != "")
            {
                if ($colCount == 0)
                    $sContent .= echo_sr('  <tr class="linklist_tbltr" id="linklist_tbltr' . ($rowCount + 1) . '">');
                if ($textAlign == $ALIGN_TOP)
                {
                    $sContent .= echo_sr('    <td class="linklist_tbltd" id="linklist_tbltd' . ($rowCount + 1) . '_' . ($colCount + 1) . '" width="' . $colWidth . '%" align="' . $align . '" style="vertical-align: bottom">');
                    if ($lilLinkList->ShowDescriptions() == true)
                        $sContent .= echo_sr('    ' . $lilLinkList->GetDescription($i) . '<br>');
                }
                else
                    $sContent .= echo_sr('    <td class="linklist_tbltd" id="linklist_tbltd' . ($rowCount + 1) . '_' . ($colCount + 1) . '" width="' . $colWidth . '%" align="' . $align . '" style="vertical-align: top">');
                $sContent .= echo_s('    <a href="' . $lilLinkList->GetLink($i) . '"');
                if ($lilLinkList->OpenInNewWindow() == true)
                    $sContent .= echo_s(' target="_blank"');
                $sContent .= echo_sr('>' . str_replace("http://", "", $lilLinkList->GetLink($i)) . '</a>');
                if ($textAlign != $ALIGN_TOP && $lilLinkList->ShowDescriptions() == true)
                    $sContent .= echo_sr('    <br>' . $lilLinkList->GetDescription($i));
                $sContent .= echo_sr('    </td>');
                $colCount ++;
                if ($colCount == $cols)
                {
                    $colCount = 0;
                    $rowCount ++;
                    $sContent .= echo_sr('  </tr>');
                }
            }
        }
        $sContent .= echo_sr('</table>');

        return $sContent;
    }
    
    // Insert a sitemap
    function build_site_sitemap()
    {
        global $PAGES_FOLDER;
        global $FILTER_UNLOCKED;
        global $SITE_MAIN_SITE;

        $sContent = "";
        $rowCount = 0;
        $page = new cPage;
        $pageList = new cPageList;

        $page->SetFolder(retrieve_absolute_path($PAGES_FOLDER));
        $pageList->SetFolder(retrieve_absolute_path($PAGES_FOLDER));
        $pageList->LoadPageList($FILTER_UNLOCKED);
        $pageList->SortPageList(4); // Sort by position

        $sContent .= echo_sr('<table border="0" width="100%" class="sitemap_tbl">');
        $list = $pageList->GetPageList();
        foreach ($list as $value)
        {
            $page->LoadPageFromId($value);
            $sContent .= echo_sr('  <tr class="sitemap_tbltr" id="sitemap_tbltr' . ($rowCount + 1) . '">');
            if ($page->GetType() != PAGETYPE_LINK)  // No link!
                $sContent .= echo_sr('    <td class="sitemap_tbltd" id="sitemap_tbltd' . ($rowCount + 1) . '"><a href="' . $SITE_MAIN_SITE . '?page=' . $page->GetId() . '">' . $page->GetTitle() . '</a></td>');
            else
                $sContent .= echo_sr('    <td class="sitemap_tbltd" id="sitemap_tbltd' . ($rowCount + 1) . '"><a href="' . $page->GetLink() . '">' . $page->GetTitle() . '</a></td>');
            $sContent .= echo_sr('  </tr>');
            $rowCount ++;
        }
        $sContent .= echo_sr('</table>');

        return $sContent;
    }

    // Insert a newsletter form
    function build_site_newsletter($naviLevelsOverride = false, $textAlign)
    {
        global $FORM_DEFTEXTALIGN, $ALIGN_TOP, $SITE_FORMSECURITY;
        $sContent = "";
        $tableDescriptions = array();
        $tableValues = array();
        $tableColumns = 2;
        if ($textAlign == "")
            $textAlign = $FORM_DEFTEXTALIGN;
        if ($textAlign == $ALIGN_TOP)
            $tableColumns = 1;

        $tableDescriptions[] = get_translation('site_newsletter_email') .':';
        if (isset($_POST['newsletter_email']) == false)
            $_POST['newsletter_email'] = "";
        $tableValues[] = '<input class="newsletter_email" type="text" size="30" name="newsletter_email" value="' . $_POST['newsletter_email'] . '">';
		if ($SITE_FORMSECURITY == "1")
		{
            $checkVal = rand(10000, 99999);
        	$tableDescriptions[] = get_translation('site_formsec_checksum') . ': ' . $checkVal;
        	if (isset($_POST['formsec_check']) == false)
                $_POST['formsec_check'] = "";
        	$tableValues[] = '<input class="contact_check" type="text" name="formsec_check" value="' . $_POST['formsec_check'] . '">';
		}

        $sContent .= echo_sr('<form method="post" action="">');
        $sContent .= build_twolevel_table('newsletter', $tableDescriptions, $tableValues, $tableColumns, count($tableDescriptions));
        $sContent .= echo_sr('<br>');
		if ($SITE_FORMSECURITY == "1")
            $sContent .= echo_sr('<input type="hidden" name="formsec_checkval" value="' . $checkVal . '">');
        $sContent .= echo_sr('<input type="submit" class="newsletter_btn" name="newsletter_Order" value="' . get_translation('site_newsletter_subscribe') .'">');
        $sContent .= echo_sr('<input type="submit" class="newsletter_btn" name="newsletter_Cancel" value="' . get_translation('site_newsletter_unsubscribe') .'">');
        $sContent .= echo_sr('<input type="hidden" name="nav_levels" value="' . $naviLevelsOverride . '">');
        $sContent .= echo_sr('</form>');

        return $sContent;
    }

    // Insert a search form
    function build_site_search($naviLevelsOverride = false, $textAlign)
    {
        global $PAGES_FOLDER;
        global $FILTER_UNLOCKED;
        global $SITE_MAIN_SITE;
        global $SEARCH_MAXSTRING;
        global $FORM_DEFTEXTALIGN, $ALIGN_TOP;
        $sContent = "";
        $tableDescriptions = array();
        $tableValues = array();
        $tableColumns = 2;
        if ($textAlign == "")
            $textAlign = $FORM_DEFTEXTALIGN;
        if ($textAlign == $ALIGN_TOP)
            $tableColumns = 1;

        $tableDescriptions[] = get_translation('site_search_term') . ':';
        if (isset($_POST['search_term']) == false)
            $_POST['search_term'] = "";
        $tableValues[] = '<input class="search_term" type="text" size="30" name="search_term" value="' . $_POST['search_term'] . '">&nbsp;<input type="submit" class="search_btn" name="search_Search" value="' . get_translation('site_search_search') .'">';

        $sContent .= echo_sr('<form method="post" action="">');
        $sContent .= build_twolevel_table('search', $tableDescriptions, $tableValues, $tableColumns, count($tableDescriptions));
        $sContent .= echo_sr('<input type="hidden" name="nav_levels" value="' . $naviLevelsOverride . '">');
        $sContent .= echo_sr('</form>');

        // Search pages?
        if (isset($_POST['search_term']))
        {
            $page = new cPage;
            $pageList = new cPageList;
            $textFile = new cTextFile;

            $page->SetFolder(retrieve_absolute_path($PAGES_FOLDER));
            $pageList->SetFolder(retrieve_absolute_path($PAGES_FOLDER));
            $pageList->LoadPageList($FILTER_UNLOCKED);
            $pageList->SortPageList(4); // Sort by position
            $list = $pageList->GetPageList();
            $foundSomething = false;
            $resultString = false;
            $sContent .= echo_sr('<table border="0" width="100%" class="searchresult_tbl">');
            foreach ($list as $value)  // Search all pages...
            {
                if ($_POST['search_term'] == "")
                    break;
                $page->LoadPageFromId($value);
                if ($page->GetType() != PAGETYPE_LINK)  // No links, they cannot be searched!!
                {
                    // Search normal content
                    $resultString = find_search_string($textFile->LoadFromFile(retrieve_absolute_path($page->GetContentFile())), $_POST['search_term']);
                    // Search title/navi title content
                    if ($resultString == false)
                    {
                        $resultString = find_search_string($page->GetTitle(), $_POST['search_term']);
                        if ($resultString == false) // Navi title
                            $resultString = find_search_string($page->GetNavigationTitle(), $_POST['search_term']);
                    }
                    // Search page specific content
                    if ($resultString == false)
                    {
                        if ($page->GetType() == PAGETYPE_CONTACT)
                           $resultString = find_search_string(build_site_contact(), $_POST['search_term']);
                        if ($page->GetType() == PAGETYPE_GALLERY)
                           $resultString = find_search_string(build_site_gallery($page->m_cGallery->GetId(), $page->GetAdditionalColCount(),
                                                                                 $page->GetAdditionalParameter(), $page->GetAdditionalParameter2(),
                                                                                 $page->GetAdditionalThumbWidth(), $page->GetAdditionalThumbHeight(),
                                                                                 $page->GetAdditionalImgWidth(), $page->GetAdditionalImgHeight()), $_POST['search_term']);
                        if ($page->GetType() == PAGETYPE_YOUTUBEGALLERY)
                           $resultString = find_search_string(build_site_youtubegallery($page->m_cYouTubeGallery->GetId(), $page->GetAdditionalColCount(),
                                                                                        $page->GetAdditionalParameter(), $page->GetAdditionalParameter2(),
                                                                                        $page->GetAdditionalImgWidth(), $page->GetAdditionalImgHeight()), $_POST['search_term']);
                        if ($page->GetType() == PAGETYPE_LINKS)
                           $resultString = find_search_string(build_site_linklist($page->m_cLinkList->GetId(), $page->GetAdditionalColCount(),
                                                                                  $page->GetAdditionalParameter(), $page->GetAdditionalParameter2()), $_POST['search_term']);
                        if ($page->GetType() == PAGETYPE_SITEMAP)
                           $resultString = find_search_string(build_site_sitemap(), $_POST['search_term']);
                        if ($page->GetType() == PAGETYPE_NEWSLETTER)
                           $resultString = find_search_string(build_site_newsletter(), $_POST['search_term']);
                        if ($page->GetType() == PAGETYPE_GUESTBOOK)
                           $resultString = find_search_string(build_site_guestbook_content($page->m_cGallery->GetId()), $_POST['search_term']);
                    }
                    
                    
                    if ($resultString != false)
                    {
                        $foundSomething = true;
                        $sContent .= echo_sr('  <tr class="searchresult_tbltr">');
                        $sContent .= echo_sr('    <td class="searchresult_tbltd"><a href="' . $SITE_MAIN_SITE . '?page=' . $page->GetId() . '">' . $page->GetTitle() . '</a></td>');
                        $sContent .= echo_sr('  </tr>');
                        $sContent .= echo_sr('  <tr class="searchresult_tbltr2">');
                        $sContent .= echo_sr('    <td class="searchresult_tbltd2">' . $resultString . '</td>');
                        $sContent .= echo_sr('  </tr>');

                    }
                }
            }
            if ($foundSomething == false)  // Nothing found?
            {
                $sContent .= echo_sr('  <tr class="searchresult_tbltr">');
                $sContent .= echo_sr('    <td class="searchresult_tbltd">' . get_translation('site_search_noresulte') . '.</td>');
                $sContent .= echo_sr('  </tr>');
            }
            $sContent .= echo_sr('</table>');
        }

        return $sContent;
    }

    // Build a two level table for additional content generated (contact, form, etc.)
    function build_twolevel_table($tableName, $tableDescriptions, $tableValues, $tableColumns, $tableRows, $idValue = 1)
    {
        $sTable = "";
        $sTable .= echo_sr('<table class="' . $tableName . '_tbl" border="0">');
        for ($i = 0; $i < $tableRows; $i ++)
        {
            $sTable .= echo_sr('  <tr class="' . $tableName . '_tbltr" id="' . $tableName . '_tbltr' . $idValue .'">');
            if ($tableColumns == 2)
            {
                $sTable .= echo_sr('    <td class="' . $tableName . '_tbltd" id="' . $tableName . '_tbltd' . $idValue .'">' . $tableDescriptions[$i] . '</td>');
                $sTable .= echo_sr('    <td class="' . $tableName . '_tbltd2" id="' . $tableName . '_tbltd' . $idValue .'_1">' . $tableValues[$i] . '</td>');
            }
            else
            {
                $sTable .= echo_sr('    <td class="' . $tableName . '_tbltd" id="' . $tableName . '_tbltd' . $idValue .'">' . $tableDescriptions[$i] . '</td>');
                $sTable .= echo_sr('  </tr>');
                $sTable .= echo_sr('  <tr class="' . $tableName . '_tbltr2" id="' . $tableName . '_tbltr' . $idValue .'_1">');
                $sTable .= echo_sr('    <td class="' . $tableName . '_tbltd2" id="' . $tableName . '_tbltd' . $idValue .'_1">' . $tableValues[$i] . '</td>');
            }
            $sTable .= echo_sr('  </tr>');
            $idValue ++;
        }
        $sTable .= echo_sr('</table>');
        return $sTable;
    }

    function find_search_string($content, $search, $noHtml = true, $limitResult = true)
    {
        global $SEARCH_MAXSTRING;
        
        $resultValue = false;
        if ($noHtml == true)
        {
            $content = str_replace("<br>", " ", $content);
            $content = str_replace("<br/>", " ", $content);
            $content = str_replace("<br />", " ", $content);
            $content = str_replace("<BR>", " ", $content);
            $content = str_replace("<BR/>", " ", $content);
            $content = str_replace("<BR />", " ", $content);
            $content = strip_tags($content, "");
        }
        $resultValue = stristr($content, $search);
        if ($resultValue != false && $limitResult == true)
        {
            if (strlen($resultValue) > $SEARCH_MAXSTRING)
                $resultValue = substr($resultValue, 0, $SEARCH_MAXSTRING) . "...";
        }
        return $resultValue;
    }

    function fill_head_parameters($content)
    {
        global $SITE_DESCRIPTION;
        global $SITE_TAGS;
        global $SITE_REVISIT;
        global $SITE_CHARSET_FORMAT;
        global $THMREP_HEAD_DESCRIPTION;
        global $THMREP_HEAD_TAGS;
        global $THMREP_HEAD_REVISIT;
        global $THMREP_HEAD_CHARSET;

        $content = str_replace($THMREP_HEAD_DESCRIPTION, $SITE_DESCRIPTION, $content);
        $content = str_replace($THMREP_HEAD_TAGS, $SITE_TAGS, $content);
        $content = str_replace($THMREP_HEAD_REVISIT, $SITE_REVISIT, $content);
        $content = str_replace($THMREP_HEAD_CHARSET, $SITE_CHARSET_FORMAT, $content);

        return $content;
    }
    
    function fill_site_parameters($content, $author, $modified)
    {
        global $SITE_TITLE;
        global $THMREP_SITE_TITLE;
        global $THMREP_SITE_DATE;
        global $THMREP_SITE_TIME;
        global $THMREP_SITE_YEAR;
        global $THMREP_SITE_AUTHOR;
        global $THMREP_SITE_MODIFIED;

        $content = str_replace($THMREP_SITE_TITLE, $SITE_TITLE, $content);
        $content = str_replace($THMREP_SITE_DATE, date("Y-m-d"), $content);
        $content = str_replace($THMREP_SITE_TIME, date("H:i:s"), $content);
        $content = str_replace($THMREP_SITE_YEAR, date("Y"), $content);
        $content = str_replace($THMREP_SITE_AUTHOR, $author, $content);
        $content = str_replace($THMREP_SITE_MODIFIED, $modified, $content);

        return $content;
    }
    
    function fill_titles($content, $siteTitle, $pageTitle)
    {
        global $THMREP_HEAD_TITLE;
        global $THMREP_BODY_TITLE;
        
        $content = str_replace($THMREP_HEAD_TITLE, $siteTitle, $content);
        $content = str_replace($THMREP_BODY_TITLE, $pageTitle, $content);

        return $content;
    }
    
    function fill_content($content, $pageContent, $pageAddContent = "", $pageAddContent2 = "")
    {
        global $THMREP_BODY_CONTENT;
        global $THMREP_BODY_ADDCONTENT;
        global $THMREP_BODY_ADDCONTENT2;

        $content = str_replace($THMREP_BODY_CONTENT, $pageContent, $content);
        $content = str_replace($THMREP_BODY_ADDCONTENT, $pageAddContent, $content);
        $content = str_replace($THMREP_BODY_ADDCONTENT2, $pageAddContent2, $content);

        return $content;
    }
    
    function fill_emptyvars($content)
    {
        // Replace all $$THM_...$$ that might no be used!!
        global $THMREP_VAR_PATTERN;
        $content = preg_replace($THMREP_VAR_PATTERN, "", $content);
        return $content;
    }

    function send_mail($receiver, $title, $message, $sender)
    {
        global $MAIL_FOLDER;
        global $SITE_CHARSET_FORMAT;
        global $LINE_FEED;
        $cEmail = new cMail;

        $mailHeader = $sender . $LINE_FEED;
        // HTML mail header
        $mailHeader .= "MIME-Version: 1.0" . $LINE_FEED;
        $mailHeader .= "Content-Type: text/html; charset=" . $SITE_CHARSET_FORMAT;
        
        $message = str_replace($LINE_FEED, "<br>", $message);

        return $cEmail->SendMailByParams($receiver, $title, $message, $mailHeader, retrieve_absolute_path($MAIL_FOLDER));
    }

    // Echo with linefeed
    function echo_r($sString)
    {
        global $LINE_FEED;
        echo ("$sString" . $LINE_FEED);
    }
    
    // Echo string with linefeed
    function echo_sr($sString)
    {
        global $LINE_FEED;
        return $sString . $LINE_FEED;
    }

    // Echo string
    function echo_s($sString)
    {
        return $sString;
    }

    function retrieve_absolute_path($fileName)
    {
        if (substr($fileName, 0, 3) == "../")
            return substr($fileName, 3);
        return $fileName;
    }

    // Print error message
    function print_error_message($msgString)
    {
        global $ERROR_IMAGE;

        echo_r ('<table class="error_tbl">');
        echo_r ('<tr>');
        echo_r ('  <td><img src="' . retrieve_absolute_path($ERROR_IMAGE) . '" alt=""></td>');
        echo_r ('  <td><b>' . $msgString . '</b><br></td>');
        echo_r ('</tr></table>');
    }

    // Build error message
    function build_error_message($msgString, $pageContent)
    {
        global $ERROR_IMAGE;

        $sError = "";
        $sError = $sError . echo_sr('<table class="error_tbl">');
        $sError = $sError . echo_sr('<tr>');
        $sError = $sError . echo_sr('  <td><img src="' . retrieve_absolute_path($ERROR_IMAGE) . '" alt=""></td>');
        $sError = $sError . echo_sr('  <td><b>' . $msgString . '</b><br></td>');
        $sError = $sError . ('</tr></table>');

        return inject_into_body($sError, $pageContent);
    }
    
    // Inject something into body content
    function inject_into_body($injectCode, $pageContent, $bAtBeginning = true)
    {
        global $LINE_FEED;
        if ($bAtBeginning == true)
            return str_replace("<body>", "<body>" . $LINE_FEED . $injectCode, $pageContent);

        return str_replace("</body>", $injectCode . $LINE_FEED . "</body>", $pageContent);
    }

    // Inject something into head content
    function inject_into_head($injectCode, $pageContent, $bAtBeginning = true)
    {
        global $LINE_FEED;
        if ($bAtBeginning == true)
            return str_replace("<head>", "<head>" . $LINE_FEED . $injectCode, $pageContent);

        return str_replace("</head>", $injectCode . $LINE_FEED . "</head>", $pageContent);
    }

    // Log a message
    function log_message($messageText)
    {
       global $ADMIN_LOG_FILE;
       global $MAX_LOG_SIZE;
       global $ADMIN_LOG_ARCHIVE;

	   $count = new class_counter;
       $count->set_files("", retrieve_absolute_path($ADMIN_LOG_FILE), "", retrieve_absolute_path($ADMIN_LOG_ARCHIVE));   // logging only
	   $count->set_max_logsize($MAX_LOG_SIZE);
	   $count->set_count_log(false, true);  // logging only
	   $count->increase($messageText);
    }

    // Retrieve a translation
    function get_translation($resString)
    {
        global $ADMIN_LANGUAGE_FILE;
        $trans = new cTranslation;
        $trans->SetTranslationFile($ADMIN_LANGUAGE_FILE);

        return $trans->GetTranslation($resString);
    }
?>