<?php

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

File:         mod_admin.php
Description:  Functions for the administrative area

*/

    include "mod_config_admin.php";
    include "class_translation.php";
    include "class_count.php";
    include "class_textfile.php";
    include "class_pageimage.php";
    include "class_pageimagelist.php";

    // functions
    function print_admin_header($titleString, $printLogout = false, $logoutString = "", $helpLink = "", $backLink = true, $backString = "", $backLink2 = "", $backString2 = "", $finish = true)
    {
        global $ADMIN_HEADER_IMAGE;
        global $ADMIN_MAIN_SITE;
        global $SITE_TITLE;
        global $ADMIN_SESS_USER;
        global $SITE_CHARSET_FORMAT;

        ini_set("default_charset", $SITE_CHARSET_FORMAT);

        // Init session before HTML output!!
        echo_r ('<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">');
        echo_r ('<html>');
        echo_r ('<head><title>' . $SITE_TITLE . ' Administration ' . $titleString . '</title>');
        echo_r ('<link rel=stylesheet type="text/css" href="../css/admin.css">');
        echo_r ('<meta http-equiv="Content-Type" content="text/html; charset=' . $SITE_CHARSET_FORMAT . '">');
        if ($finish == true)
            finish_admin_header($titleString, $printLogout, $logoutString, $helpLink, $backLink, $backString, $backLink2, $backString2);
    }

    function print_wysiwyg_header()
    {
        global $ADMIN_LANGUAGE;
        global $ADMIN_EDITOR_FILE;
        global $PAGEIMAGES_LIST;
        
        echo_r ('<script type="text/javascript" src="' . $ADMIN_EDITOR_FILE . '"></script>');
        echo_r ('<script type="text/javascript">');
	    echo_r ('tinyMCE.init({');
	    echo_r ('// General options');
	    echo_r ('mode : "textareas",');
	    echo_r ('theme : "advanced",');
	    if ($ADMIN_LANGUAGE == "de")
	    echo_r ('language : "de",');
	    echo_r ('plugins : "autolink,lists,pagebreak,layer,table,advhr,advimage,advlink,iespell,inlinepopups,insertdatetime,preview,searchreplace,contextmenu,paste,directionality,fullscreen,noneditable,nonbreaking,xhtmlxtras,template,wordcount,advlist",');
	    echo_r ('// Image list - machine generated');
        echo_r ('external_image_list_url : "' . $PAGEIMAGES_LIST . '",');
	    echo_r ('// Theme options');
	    echo_r ('theme_advanced_buttons1 : "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,formatselect,fontselect,fontsizeselect",');
	    echo_r ('theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,code,|,insertdate,inserttime,preview,|,forecolor,backcolor",');
	    echo_r ('theme_advanced_buttons3 : "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,media,advhr,|,print,|,ltr,rtl,|,fullscreen",');
	    echo_r ('theme_advanced_buttons4 : "insertlayer,moveforward,movebackward,absolute,|,styleprops,|,cite,abbr,acronym,del,ins,attribs,|,visualchars,nonbreaking,template,pagebreak,restoredraft",');
	    echo_r ('theme_advanced_toolbar_location : "top",');
	    echo_r ('theme_advanced_toolbar_align : "left",');
	    echo_r ('theme_advanced_statusbar_location : "bottom",');
	    echo_r ('theme_advanced_resizing : true,');
	    echo_r ('// Content CSS');
	    echo_r ('content_css : "../css/editor.css"');
	    echo_r ('});');
	    echo_r ('</script>');
    }
    
    function generate_pageimage_list()
    {
        global $FILTER_UNLOCKED, $PAGEIMAGES_FOLDER, $LINE_FEED, $PAGEIMAGES_LIST;
        $pgi = new cPageImage;
        $pgiList = new cPageImageList;
        $cFile = new cTextFile;
        $cContent = "// Alterante WebKit machine generated file - do not edit." . $LINE_FEED;
        $cContent .= "var tinyMCEImageList = new Array(" . $LINE_FEED . "// Name, URL" . $LINE_FEED;
        
        $pgi->SetFolder($PAGEIMAGES_FOLDER);
        $pgiList->SetFolder($PAGEIMAGES_FOLDER);
        $pgiList->LoadPageImageList($FILTER_UNLOCKED);
        $pgiList->SortByTitle(true);
        $listOfPageImages = $pgiList->GetPageImageList();

        for ($d = 0; $d < count($listOfPageImages); $d ++)
        {
            $pgi->LoadPageImageFromId($listOfPageImages[$d]);
            if ($d == (count($listOfPageImages) - 1))
                $cContent .= ('["' . $pgi->GetTitle() . '", "' . $pgi->GetImageFile() . '"]' . $LINE_FEED);
            else
                $cContent .= ('["' . $pgi->GetTitle() . '", "' . $pgi->GetImageFile() . '"],' . $LINE_FEED);
        }
        $cContent .= ");";
        // Save list content to .js file
        $cFile->SaveToFile($PAGEIMAGES_LIST, $cContent);
    }

    function finish_admin_header($titleString, $printLogout = false, $logoutString = "", $helpLink = "", $backLink = true, $backString = "", $backLink2 = "", $backString2 = "")
    {
        global $ADMIN_HEADER_IMAGE;
        global $HELP_IMAGE;
        global $ADMIN_MAIN_SITE;
        global $SITE_TITLE;
        global $ADMIN_SESS_USER;
        global $SITE_CHARSET_FORMAT;

        echo_r ('</head>');
        echo_r ('<body>');
        echo_r ('<center>');
        echo_r ('<div class="admin_outer_div">');
        echo_r ('<div class="admin_logo_div">');
        if ($backLink == true)
            echo_r ('   <a href="' . $ADMIN_MAIN_SITE . '" style="padding: 0px; border: 0px; margin: 0px;">');
  //      if ($backLink == true)
  //          echo_r ('  <img border="0" src="'. $ADMIN_HEADER_IMAGE .'" alt="' . $SITE_TITLE . '" style="cursor: pointer;" onClick="JavaScript:window.location.href=\'' . $ADMIN_MAIN_SITE . '\'">');
   //     else
        echo_r ('  <img border="0" style="border-image: 0px;" src="'. $ADMIN_HEADER_IMAGE .'" alt="' . $SITE_TITLE . '">');
        if ($backLink == true)
            echo_r ('   </a>');
        echo_r ('</div>');
        echo_r ('<div class="admin_top_div">');
        echo_r ('<form method="post" action="">');
        echo_r ('  <div class="admin_top_side_div">');
        echo_r ('    <div class="admin_top_side_content_div">');
        if ($backLink == true && $backString != "")
        {
            echo_r ('      <input class="action_btn" type="button" name="admin_Main" value="' . $backString . '" onClick="JavaScript:window.location.href=\'' . $ADMIN_MAIN_SITE . '\'">');
            if ($backLink2 != "" && $backString2 != "")
                echo_r ('      <input class="action_btn" type="button" name="admin_Prev" value="' . $backString2 . '" onClick="JavaScript:window.location.href=\'' . $backLink2 . '\'">');
        }
        echo_r ('    </div>');
        echo_r ('  </div>');
        echo_r ('  <div class="admin_top_middle_div">');
        echo_r ('    <div class="admin_top_middle_content_div"><b>' . $SITE_TITLE . ': Administration' . $titleString . '</b></div>');
        echo_r ('  </div>');
        echo_r ('  <div class="admin_top_side_div">');
        echo_r ('    <div class="admin_top_side_content_div">');
        if ($printLogout == true)
        {
            echo_r('      <input class="action_btn" type="submit" name="admin_Logout" value="' . $logoutString . ' [' . $_SESSION[$ADMIN_SESS_USER] . ']">');
            if ($helpLink != "")
                echo_r('      <a href="' . $helpLink . '" target="_blank"><img src="' . $HELP_IMAGE . '" title="' . get_translation("admin_help") . '" alt="' . get_translation("admin_help") . '"></a>');
        }
        echo_r ('    </div>');
        echo_r ('  </div>');
        echo_r ('</form>');
        echo_r ('</div>');
        echo_r ('<div class="admin_clear_float"></div>');
    }

    function print_bottom_links($nameLeft, $valueLeft, $nameRight = "", $valueRight = "", $withForm = true)
    {
        echo_r ('<div class="admin_bottom_spacer"></div>');
        if ($withForm == true)
            echo_r ('<form method="post" action="">');
        echo_r ('<div class="admin_bottom_div">');
        echo_r ('  <div class="admin_bottom_content_div">');
        echo_r ('    <input type="submit" class="action_btn" name="' . $nameLeft . '" value="' . $valueLeft . '">');
        if ($nameRight != "")
            echo_r ('    <input type="submit" class="action_btn" name="' . $nameRight . '" value="' . $valueRight . '">');
        echo_r ('  </div>');
        echo_r ('</div>');
        if ($withForm == true)
            echo_r ('</form>');
    }

    function print_admin_footer()
    {
        echo_r ('</div>');
        echo_r ('</center>');
        echo_r ('</body>');
        echo_r ('</html>');
    }
    
    function print_error_message($msgString)
    {
        global $ERROR_IMAGE;

        echo_r ('  <div class="admin_error_div">');
        echo_r ('    <div class="admin_error_content_div">');
        echo_r ('      <b>- ' . $msgString . '</b>');
        echo_r ('    </div>');
        echo_r ('  </div>');
    }
    
    function log_in($userName, $userType)
    {
        global $ADMIN_SESS_USER;
        global $ADMIN_SESS_TYPE;
        session_start();
        $_SESSION[$ADMIN_SESS_USER] = $userName;
        $_SESSION[$ADMIN_SESS_TYPE] = $userType;
    }
    
    function log_out()
    {
        global $ADMIN_LOGIN_SITE;
        session_unset();
        session_destroy();
        header ('location: '. $ADMIN_LOGIN_SITE);
    }
    
    function get_user_name()
    {
        global $ADMIN_SESS_USER;
        return $_SESSION[$ADMIN_SESS_USER];
    }
    
    function check_login()
    {
        global $ADMIN_LOGIN_SITE;
        global $ADMIN_SESS_USER;
        global $ADMIN_SESS_TYPE;
        session_start();
        if (isset($_SESSION[$ADMIN_SESS_USER]) == false || $_SESSION[$ADMIN_SESS_USER] == "" || isset($_SESSION[$ADMIN_SESS_TYPE]) == false || $_SESSION[$ADMIN_SESS_TYPE] == "")
            header ('location: ' . $ADMIN_LOGIN_SITE);
        if (isset($_POST['admin_Logout']))
        {
            log_message ('User ' . get_user_name() . ' logged out');
            log_out();
        }
    }
    
    function get_auth()
    {
        global $ADMIN_SESS_TYPE;
        if ($_SESSION[$ADMIN_SESS_TYPE] == "")
            return -1;
        return $_SESSION[$ADMIN_SESS_TYPE];
    }
    
    function user_is_customer()
    {
        return (get_auth() < 1);
    }
    function user_is_reporter()
    {
        return (get_auth() == 1);
    }
    function user_is_admin()
    {
        return (get_auth() == 3);
    }
    
    function retrieve_extension($fileName)
    {
        $iCount = 0;
        for ($i = strlen($fileName) - 1; $i >= 0; $i --)
        {
            $iCount ++;
            if ($fileName[$i] == '.')
            {
                return substr($fileName, -$iCount);
            }
        }
        return $fileName;
    }
    
    function retrieve_absolute_path($fileName)
    {
        if (substr($fileName, 0, 3) == "../")
            return substr($fileName, 3);
        return $fileName;
    }

    function echo_r($strString)
    {
        global $LINE_FEED;
        echo ($strString . $LINE_FEED);
    }
    
    function log_message($messageText)
    {
       global $ADMIN_LOG_FILE;
       global $MAX_LOG_SIZE;
       global $ADMIN_LOG_ARCHIVE;
       
	   $count = new class_counter;
       $count->set_files("", $ADMIN_LOG_FILE, "", $ADMIN_LOG_ARCHIVE);   // logging only
	   $count->set_max_logsize($MAX_LOG_SIZE);
	   $count->set_count_log(false, true);  // logging only
	   $count->increase($messageText);
    }
    
    function check_image_extension($fileName)
    {
        $fileExt = strtolower(retrieve_extension($fileName));
        if ($fileExt != ".gif" && $fileExt != ".jpg" && $fileExt != ".jpeg" && $fileExt != ".png")
            return false;

        return true;
    }

    function check_ico_extension($fileName)
    {
        $fileExt = strtolower(retrieve_extension($fileName));
        if ($fileExt != ".ico")
            return false;

        return true;
    }

    function check_music_extension($fileName)
    {
        $fileExt = strtolower(retrieve_extension($fileName));
        if ($fileExt != ".mp3" && $fileExt != ".ogg")
            return false;

        return true;
    }

    function resize_image($srcName, $tmpName, $destName, $imgDestWidth, $imgDestHeight, $noResize = false, $force = false, $exactly = true, $backgroundColor = "0x00FFFFFF", $allowPortrait = false)
    {
        // Check, if resize is necessary
        $sizes = getimagesize($tmpName);
        $srcWidth = $sizes[0];
        $srcHeight = $sizes[1];
        // Swap dest height/width, if portrait is allowed and dest image measurements differ
        if ($allowPortrait == true)
        {
            if ((($imgDestWidth > $imgDestHeight) && ($srcWidth < $srcHeight)) ||
                (($imgDestWidth < $imgDestHeight) && ($srcWidth > $srcHeight)))
            {
                $tmp = $imgDestWidth;
                $imgDestWidth = $imgDestHeight;
                $imgDestHeight = $tmp;
            }
        }
        // Just copy?
        if (($srcWidth == $imgDestWidth && $srcHeight == $imgDestHeight) || ($noResize == true && $force == false))
        {
            return @ copy ($tmpName, $destName);
        }
        if (($srcWidth <= $imgDestWidth && $srcHeight <= $imgDestHeight) && $force == false)
        {
            return @ copy ($tmpName, $destName);
        }
        // Resize it...
        $imgSrcExt = strtolower(retrieve_extension($srcName));
        // Load source image
        if ($imgSrcExt == ".jpg" || $imgSrcExt == ".jpeg")
            $imgSrc = imagecreatefromjpeg($tmpName);
        else if ($imgSrcExt == ".png")
            $imgSrc = imagecreatefrompng($tmpName);
        else if ($imgSrcExt == ".gif")
            $imgSrc = imagecreatefromgif($tmpName);
        else
            return false;  // unknown image type!!

        //Calculate the image ratio
        // Exactly?
        if ($exactly == true)
        {
            $imgRatio = ($srcWidth / $srcHeight);
            if ($imgRatio > 1)
            {
                $newWidth = $imgDestWidth;
                $newHeight = ($imgDestWidth / $imgRatio);
            }
            else
            {
                $newHeight = $imgDestHeight;
                $newWidth = ($imgDestHeight * $imgRatio);
            }
        }
        else
        {
            if ($srcWidth >= $srcHeight)
            {
                $newWidth = $imgDestWidth;
                $newHeight = $srcHeight / ($srcWidth / $imgDestWidth);
            }
            else
            {
                $newHeight = $imgDestHeight;
                $newWidth =  $srcWidth / ($srcHeight / $imgDestHeight);
            }
            $imgDestWidth = $newWidth;
            $imgDestHeight = $newHeight;
        }
        log_message ('User ' . get_user_name() . ' image upload must be resized to ' . $imgDestWidth . ' x ' . $imgDestHeight . ' - origin: ' . $srcWidth . ' x ' . $srcHeight);

        $newImage = imagecreatetruecolor($imgDestWidth, $imgDestHeight);
        // Use a white background, default is black....
//        $fillColor = ImageColorAllocate ($newImage, 255, 255, 255);
        $backgroundColor = hexdec($backgroundColor);
        imagefill($newImage, 1, 1, $backgroundColor);  // Does not work on PHP 5.3??
        imagefilledrectangle($newImage, 0, 0, $imgDestWidth, $imgDestHeight, $backgroundColor);
        if ($newHeight != $imgDestHeight)  // center horizontal
            ImageCopyResized($newImage, $imgSrc, 0, ($imgDestHeight - $newHeight) / 2, 0, 0, $newWidth, $newHeight, $srcWidth, $srcHeight);
        else  // center vertical
            ImageCopyResized($newImage, $imgSrc, ($imgDestWidth - $newWidth) / 2, 0, 0, 0, $newWidth, $newHeight, $srcWidth, $srcHeight);
        //Save the target image
        if ($imgSrcExt == ".jpg" || $imgSrcExt == ".jpeg")
            imagejpeg($newImage, $destName);
        if ($imgSrcExt == ".png")
            imagepng($newImage, $destName);
        if ($imgSrcExt == ".gif")
            imagegif($newImage, $destName);
        ImageDestroy($newImage);
        ImageDestroy($imgSrc);
        return true;
    }

    function get_imagezoomed($img_url, $width, $height, $max_width, $max_height, $title, $alt_text, $stretch = false)
    {
        $res_height = $max_height;
        $res_width = $max_width;
        
        if ($width != "" && $width > 0 && $height != "" && $height > 0)  // No image size given
        {
            if ($width < $max_width && $height < $max_height && $stretch == false)  // Image is smaller than limits
            {
                $res_width = $width;
                $res_height = $height;
            }
            else
            {
                if ($width >= $height)
                {
                    $res_width = $max_width;
                    $res_height = $height / ($width / $max_width);
                }
                else
                {
                    $res_height = $max_height;
                    $res_width =  $width / ($height / $max_height);
                }
            }
        }

        return '<img src="' . $img_url . '" width="' . (int)$res_width . '" height="' . (int)$res_height . '" title="' . $title . '" alt="' . $alt_text . '">';
    }

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

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

    function sort_table($tableData, $sortColumn, $sortAscending)
    {
        if (count($tableData) < 1)
            return $tableData;

        // Sort table?
        if ($sortColumn != -1)
        {
            if (count($tableData) > 0)
            {
                foreach ($tableData as $key => $row)
                {
                    $sortArray[$key]    = strtolower($row[$sortColumn]);
//                    $auflage[$key] = $row['Auflage'];       // Example to sort by 2nd parameter, keep it here!!
                }
                // Check for numeric sort
                $numericSort = false;
                if (isset($sortArray[0]) == true && isset($sortArray[1]) == true)
                {
                    // If the first two elements are numeric, we assume the column is numeric
                    if (is_numeric($sortArray[0]) == true && is_numeric($sortArray[1]) == true)
                        $numericSort = true;
                }
                if ($sortAscending == true)
                {
                    if ($numericSort == true)
                        array_multisort($sortArray, SORT_ASC, SORT_NUMERIC, $tableData);
                    else
                        array_multisort($sortArray, SORT_ASC, SORT_STRING, $tableData);
                }
                else
                {
                    if ($numericSort == true)
                        array_multisort($sortArray, SORT_DESC, SORT_NUMERIC, $tableData);
                    else
                        array_multisort($sortArray, SORT_DESC, SORT_STRING, $tableData);
                }
            }
        }

        return $tableData;
    }

    function update_index_file($src, $dst)
    {
        global $SITE_TITLE;
        global $SITE_DESCRIPTION;
        global $SITE_TAGS;
        global $SITE_CHARSET_FORMAT;
        global $SITE_REVISIT;
        global $THMREP_HEAD_TITLE;
        global $THMREP_HEAD_DESCRIPTION;
        global $THMREP_HEAD_TAGS;
        global $THMREP_HEAD_REVISIT;
        global $THMREP_HEAD_CHARSET;

        $cFile = new cTextFile;
        
        // Now update the index.htm forward page
        $indexText = $cFile->LoadFromFile($src);
        $indexText = str_replace($THMREP_HEAD_TITLE, $SITE_TITLE, $indexText);
        $indexText = str_replace($THMREP_HEAD_DESCRIPTION, $SITE_DESCRIPTION, $indexText);
        $indexText = str_replace($THMREP_HEAD_TAGS, $SITE_TAGS, $indexText);
        $indexText = str_replace($THMREP_HEAD_REVISIT, $SITE_REVISIT, $indexText);
        $indexText = str_replace($THMREP_HEAD_CHARSET, $SITE_CHARSET_FORMAT, $indexText);
        return $cFile->SaveToFile($dst, $indexText);
    }
    
    function transform_keep_html($inString)
    {
       global $SITE_CHARSET_FORMAT;
       $resString = htmlentities($inString, ENT_COMPAT, $SITE_CHARSET_FORMAT);
       $resString = str_replace("&lt;","<",$resString);
       $resString = str_replace("&gt;",">",$resString);
       $resString = str_replace("&quot;",'"',$resString);
       $resString = str_replace("&amp;",'&',$resString);
       return $resString;
    }

?>