MSV FM

dot.antimicrobial@66.96.161.157: ~ $
Path : /hermes/sb_web/b744/kanevskylaw.com/admin/classes/
File Upload :
Current < : /hermes/sb_web/b744/kanevskylaw.com/admin/classes/class.template.php

<?php

class Template extends Admin
{
    var $blockData;
    var $addHeader;
    var $leftMenu;
    var $url;
    var $path;
    var $fileExtensions;
    var $fileTmpDir;
    var $request;
    var $jRequest;
    var $pager;

    function __construct($leftMenu)
    {
        parent::__construct();

        $connector = "";
        foreach ($_GET as $key => $value) {
            $value     = strtolower(preg_replace("/[^0-9a-zA-Z\-\,\.\s]/", "", $value));
            $$key      = $value;
            $this->url .= $connector . $key . "=" . $value;
            if (empty($connector)) {
                $connector = "&";
            }
        }

        $this->fileExtensions = array(
            "images" => array("jpg", "gif", "png"),
            "files"  => array("pdf", "txt", "rtf", "csv", "xml", "doc", "docx", "xls", "xlsx", "ppt", "pptx"),
        );
        $this->fileTmpDir     = $_SERVER["DOCUMENT_ROOT"] . "/tmp_uploads/";
        $this->url            = trim($this->url);
        $this->leftMenu       = $leftMenu;
        $this->path           = "interfacelevel/";
        $this->jRequest       = 0;
        $this->request        = array(
            "option" => isset($option) ? $option : "",
            "action" => isset($action) ? $action : "",
            "id"     => isset($id) ? $id : 0,
            "ext"    => isset($ext) ? $ext : "",
        );
        $this->pager          = array("pager" => "", "page" => isset($_GET["page"]) ? $_GET["page"] : 1, "items" => 100, "limit" => 1, "total" => 0);

        $this->fnc_AddHeader('<script>var url = "' . $this->url . '"</script>');
    }

    function fnc_Init()
    {
        if ($this->adminID) {
            $allowedSections = array();
            if (isset($this->leftMenu[$this->adminPermission])) {
                $tmpMenu        = $this->leftMenu[$this->adminPermission];
                $this->leftMenu = array();
                foreach ($tmpMenu as $keyM => $valueM) {
                    $this->leftMenu["lm_" . $keyM] = 0;
                    foreach ($valueM as $keyS) {
                        $allowedSections[]             = str_replace("_", "-", $keyS);
                        $this->leftMenu["sm_" . $keyS] = 0;
                    }
                }
            }

            if (!strcmp($this->adminPermission, "A")) {
                $allowedSections[] = "sections";
            }

            $dirName = $this->path . "modules/" . $this->request["option"];

            if (!strcmp($this->request["option"], "redirect")) {
                $this->fnc_Redirect();
            } elseif (!strcmp($this->request["option"], "logout")) {
                $this->Logout();
            } elseif (!strcmp($this->request["option"], "upload")) {
                $this->fnc_TemporaryUpload();
            } elseif (in_array($this->request["option"], $allowedSections) && is_dir($dirName) && file_exists($dirName . "/{$this->request["option"]}.php")) {
                require_once($dirName . "/{$this->request["option"]}.php");
                ExecModule($this->request["action"]);
            } else {
                $tempBlock = $this->fnc_Template($this->path . "tpl/main");
                eval("\$this->blockData = \"$tempBlock\";");
            }
        } else {
            $this->jRequest = 1;
            $this->Login();

            $msg = $this->GetErrorMessage();

            $tempBlock = $this->fnc_Template("./tpl/login");
            eval("\$this->blockData = \"$tempBlock\";");
        }

        $this->fnc_Display();
    }

    function fnc_GetSubMenu()
    {
        global $CLASSDB;

        $menu = "";
        $res  = $CLASSDB->query("SELECT sec_id, sec_title FROM {$CLASSDB->dbPrefix}sections WHERE (sec_active = 'Y') ORDER BY sec_position ASC");
        while ($row = $CLASSDB->fetch_array($res)) {
            $class = !strcmp($this->request["option"], "sections") && ($this->request["id"] == $row["sec_id"]) ? "S" : "";
            $menu  .= '<a class="sm-item' . $class . '" href="./index.php?option=sections&id=' . $row["sec_id"] . '">' . $row["sec_title"] . '</a>';
        }

        return $menu;
    }

    function fnc_GetFiles($itemID, $filesSettings)
    {
        global $CLASSDB;

        $filesArr = array("images" => "", "files" => "", "single" => "", "mainImage" => "", "videos" => "", "lightbox" =>
        0);

        $resFiles = $CLASSDB->query("SELECT * FROM {$CLASSDB->dbPrefix}files WHERE (file_module = '{$filesSettings["module"]}') AND (file_parent = '{$itemID}') ORDER BY file_position ASC");
        while ($rowFile = $CLASSDB->fetch_array($resFiles)) {
            $fileCaption = '<textarea class="file-area" name="file-caption[' . $rowFile["file_id"] . ']">' . $rowFile['file_caption'] . '</textarea>';

            if (!strcmp($rowFile["file_type"], "V")) {
                $captionWidth = 25;
                $fileEmbed    = '
							<td valign="top" width="25%">
								<textarea class="file-area" name="file-embed[' . $rowFile["file_id"] . ']">' . $rowFile["file_embed"] . '</textarea>
							</td>';
            } else {
                $captionWidth = 50;
                $fileEmbed    = "";
            }

            if (!strcmp($rowFile["file_type"], "F")) {
                $vArr = explode(".", $rowFile["file_src"]);
                $fExt = end($vArr);
                $icon = '<a href="/files/' . $filesSettings["folder"] . $rowFile["file_src"] . '" target="_blank"><img src="' . $this->path . '/images/files/' . $fExt . '.jpg" border="0"></a>';
            } else {
                $icon = '<a href="/images/' . $filesSettings["folder"] . $rowFile["file_src"] . '" class="pirobox" rel="single" title="' . $rowFile["file_caption"] . '"><img src="/images/' . $filesSettings["folder"] . 'a-preview/' . $rowFile["file_src"] . '" border="0"></a>';

                if (!isset($filesSettings["{$rowFile["file_type"]}_caption"]) || !$filesSettings["{$rowFile["file_type"]}_caption"]) {
                    $fileCaption = "";
                }
            }

            $tempBlock = $this->fnc_Template($this->path . "tpl/files-row");
            eval("\$file = \"$tempBlock\";");

            switch ($rowFile["file_type"]) {
                case "I":
                    $filesArr["images"] .= $file;
                    break;
                case "F":
                    $filesArr["files"] .= $file;
                    break;
                case "S":
                    $filesArr["single"] .= $file;
                    break;
                case "MI":
                    $filesArr["mainImage"] .= $file;
                    break;
                case "V":
                    $filesArr["videos"] .= $file;
                    break;
            }
        }

        $tempBlock = $this->fnc_Template($this->path . "tpl/files-tbl");
        eval("\$table = \"$tempBlock\";");

        if (!empty($filesArr["images"])) {
            $filesArr["images"]   = str_replace("%CONTENT%", $filesArr["images"], $table);
            $filesArr["images"]   = str_replace("%HEADER_EMBED%", "", $filesArr["images"]);
            $filesArr["images"]   = str_replace("%CAPTION_WIDTH%", "50%", $filesArr["images"]);
            $filesArr["images"]   = str_replace("%CAPTION_LABEL%", (isset($filesSettings["I_caption"]) && $filesSettings["I_caption"] ? "Caption" : ""), $filesArr["images"]);
            $filesArr["lightbox"] = 1;
        }

        if (!empty($filesArr["files"])) {
            $filesArr["files"] = str_replace("%CONTENT%", $filesArr["files"], $table);
            $filesArr["files"] = str_replace("%HEADER_EMBED%", "", $filesArr["files"]);
            $filesArr["files"] = str_replace("%CAPTION_WIDTH%", "50%", $filesArr["files"]);
            $filesArr["files"] = str_replace("%CAPTION_LABEL%", "Caption", $filesArr["files"]);
        }

        if (!empty($filesArr["single"])) {
            $filesArr["single"]   = str_replace("%CONTENT%", $filesArr["single"], $table);
            $filesArr["single"]   = str_replace("%HEADER_EMBED%", "", $filesArr["single"]);
            $filesArr["single"]   = str_replace("%CAPTION_WIDTH%", "50%", $filesArr["single"]);
            $filesArr["single"]   = str_replace("%CAPTION_LABEL%", (isset($filesSettings["S_caption"]) && $filesSettings["S_caption"] ? "Caption" : ""), $filesArr["single"]);
            $filesArr["lightbox"] = 1;
        }

        if (!empty($filesArr["mainImage"])) {
            $filesArr["mainImage"]   = str_replace("%CONTENT%", $filesArr["mainImage"], $table);
            $filesArr["mainImage"]   = str_replace("%HEADER_EMBED%", "", $filesArr["mainImage"]);
            $filesArr["mainImage"]   = str_replace("%CAPTION_WIDTH%", "50%", $filesArr["mainImage"]);
            $filesArr["mainImage"]   = str_replace("%CAPTION_LABEL%", (isset($filesSettings["S_caption"]) && $filesSettings["S_caption"] ? "Caption" : ""), $filesArr["mainImage"]);
            $filesArr["lightbox"] = 1;
        }

        if (!empty($filesArr["videos"])) {
            $embedHeader = '<td valign="middle" class="files-header" width="25%">Embed Code</div>';

            $filesArr["videos"]   = str_replace("%CONTENT%", $filesArr["videos"], $table);
            $filesArr["videos"]   = str_replace("%HEADER_EMBED%", $embedHeader, $filesArr["videos"]);
            $filesArr["videos"]   = str_replace("%CAPTION_WIDTH%", "25%", $filesArr["videos"]);
            $filesArr["videos"]   = str_replace("%CAPTION_LABEL%", (isset($filesSettings["V_caption"]) && $filesSettings["V_caption"] ? "Caption" : ""), $filesArr["videos"]);
            $filesArr["lightbox"] = 1;
        }

        return $filesArr;
    }

    function fnc_UpdateFiles($itemID, $filesSettings)
    {
        global $CLASSDB;

        $filesToUpdate = $filesToDelete = $filesUpdatePositions = array();

        if (isset($_POST["file-delete"]) && is_array($_POST["file-delete"])) {
            $res = $CLASSDB->query("SELECT file_id, file_src, file_type FROM {$CLASSDB->dbPrefix}files WHERE (file_id IN (" . implode(",", $_POST["file-delete"]) . ")) AND (file_module = '{$filesSettings["module"]}')");
            while ($row = $CLASSDB->fetch_array($res)) {
                $targetDir       = $_SERVER["DOCUMENT_ROOT"] . "/" . (!strcmp($row["file_type"], "F") ? "files" : "images") . "/" . $filesSettings["folder"];
                $filesToDelete[] = $row["file_id"];

                $this->fnc_DeleteSingleFile($filesSettings, $targetDir, $row);
            }
        }

        if (isset($_POST["file-position"]) && is_array($_POST["file-position"])) {
            foreach ($_POST["file-position"] as $key => $value) {
                if (!in_array($key, $filesToDelete)) {
                    $res = $CLASSDB->fetch_array($CLASSDB->query("SELECT file_type, file_position FROM {$CLASSDB->dbPrefix}files WHERE (file_id = '{$key}')"));
                    if ($res["file_position"] != $value) {
                        $filesUpdatePositions[$key]["type"] = $res["file_type"];
                        $filesUpdatePositions[$key]["pos"]  = $value;
                        $filesToUpdate[$key][]              = "file_position = '" . $CLASSDB->escape_string($value) . "'";
                    }
                }
            }
        }

        if (isset($_POST["file-caption"]) && is_array($_POST["file-caption"])) {
            foreach ($_POST["file-caption"] as $key => $value) {
                if (!in_array($key, $filesToDelete)) {
                    $filesToUpdate[$key][] = "file_caption = '" . $CLASSDB->escape_string($value) . "'";
                }
            }
        }

        if (isset($_POST["file-embed"]) && is_array($_POST["file-embed"])) {
            foreach ($_POST["file-embed"] as $key => $value) {
                if (!in_array($key, $filesToDelete)) {
                    $filesToUpdate[$key][] = "file_embed = '" . $CLASSDB->escape_string($value) . "'";
                }
            }
        }

        foreach ($filesToUpdate as $key => $value) {
            if ($value) {
                $query = implode(",", $value);
                $CLASSDB->query("UPDATE {$CLASSDB->dbPrefix}files SET {$query} WHERE (file_id = '{$key}')");
            }
        }

        foreach ($filesUpdatePositions as $key => $data) {
            $type  = $data["type"];
            $value = $data["pos"];

            $res = $CLASSDB->fetch_array($CLASSDB->query("SELECT file_id, file_type FROM {$CLASSDB->dbPrefix}files WHERE (file_id <> '{$key}') AND (file_module = '{$filesSettings["module"]}') AND (file_type = '{$type}') AND (file_parent = '{$itemID}') AND (file_position = '{$value}')"));
            if ($res) {
                $position = $value;
                $res      = $CLASSDB->query("SELECT file_id FROM {$CLASSDB->dbPrefix}files WHERE (file_id <> '{$key}') AND (file_module = '{$filesSettings["module"]}') AND (file_type = '{$type}') AND (file_parent = '{$itemID}') AND (file_position >= '{$value}') ORDER BY file_position ASC");
                while ($row = $CLASSDB->fetch_array($res)) {
                    $position ++;
                    $CLASSDB->query("UPDATE {$CLASSDB->dbPrefix}files SET file_position = '{$position}' WHERE (file_id = '{$row["file_id"]}')");
                }
            }
        }
    }

    function fnc_DeleteSingleFile($filesSettings, $targetDir, $res)
    {
        global $CLASSDB;

        if (isset($filesSettings["thumbs"][$res["file_type"]])) {
            foreach ($filesSettings["thumbs"][$res["file_type"]] as $folder) {
                unlink($targetDir . (empty($folder["folder"]) ? "" : $folder["folder"] . "/") . $res["file_src"]);
            }
        } else {
            unlink($targetDir . $res["file_src"]);
        }

        $CLASSDB->query("DELETE FROM {$CLASSDB->dbPrefix}files WHERE (`file_id` = '{$res["file_id"]}')");
    }

    function fnc_TemporaryUpload()
    {
        $this->jRequest = 1;

        header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
        header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
        header("Cache-Control: no-store, no-cache, must-revalidate");
        header("Cache-Control: post-check=0, pre-check=0", false);
        header("Pragma: no-cache");

        $targetDir        = $_SERVER["DOCUMENT_ROOT"] . "/tmp_uploads/";
        $cleanupTargetDir = true;
        $maxFileAge       = 5 * 3600;

        @set_time_limit(5 * 60);

        $chunk    = isset($_REQUEST["chunk"]) ? intval($_REQUEST["chunk"]) : 0;
        $chunks   = isset($_REQUEST["chunks"]) ? intval($_REQUEST["chunks"]) : 0;
        $fileName = isset($_REQUEST["name"]) ? $_REQUEST["name"] : '';
        $fileName = preg_replace('/[^\w\._]+/', '_', $fileName);

        if ($chunks < 2 && file_exists($targetDir . $fileName)) {
            $ext        = strrpos($fileName, '.');
            $fileName_a = substr($fileName, 0, $ext);
            $fileName_b = substr($fileName, $ext);

            $count = 1;
            while (file_exists($targetDir . $fileName_a . '_' . $count . $fileName_b)) {
                $count ++;
            }

            $fileName = $fileName_a . '_' . $count . $fileName_b;
        }

        $filePath = $targetDir . $fileName;

        if (!file_exists($targetDir)) {
            @mkdir($targetDir);
        }

        if ($cleanupTargetDir) {
            if (is_dir($targetDir) && ($dir = opendir($targetDir))) {
                while (($file = readdir($dir)) !== false) {
                    $tmpfilePath = $targetDir . $file;

                    if (preg_match('/\.part$/', $file) && (filemtime($tmpfilePath) < time() - $maxFileAge) && ($tmpfilePath != "{$filePath}.part")) {
                        @unlink($tmpfilePath);
                    }
                }

                closedir($dir);
            } else {
                $this->blockData = '{"jsonrpc" : "2.0", "error" : {"code": 100, "message": "Failed to open temp directory."}, "id" : "id"}';
            }
        }

        if (empty($this->blockData)) {
            if (isset($_SERVER["HTTP_CONTENT_TYPE"])) {
                $contentType = $_SERVER["HTTP_CONTENT_TYPE"];
            }

            if (isset($_SERVER["CONTENT_TYPE"])) {
                $contentType = $_SERVER["CONTENT_TYPE"];
            }

            if (strpos($contentType, "multipart") !== false) {
                if (isset($_FILES['file']['tmp_name']) && is_uploaded_file($_FILES['file']['tmp_name'])) {
                    $out = @fopen("{$filePath}.part", $chunk == 0 ? "wb" : "ab");
                    if ($out) {
                        $in = @fopen($_FILES['file']['tmp_name'], "rb");

                        if ($in) {
                            while ($buff = fread($in, 4096)) {
                                fwrite($out, $buff);
                            }
                        } else {
                            $this->blockData = '{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}';
                        }

                        @fclose($in);
                        @fclose($out);
                        @unlink($_FILES['file']['tmp_name']);
                    } else {
                        $this->blockData = '{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}';
                    }
                } else {
                    $this->blockData = '{"jsonrpc" : "2.0", "error" : {"code": 103, "message": "Failed to move uploaded file."}, "id" : "id"}';
                }
            } else {
                $out = @fopen("{$filePath}.part", $chunk == 0 ? "wb" : "ab");
                if ($out) {
                    $in = @fopen("php://input", "rb");

                    if ($in) {
                        while ($buff = fread($in, 4096)) {
                            fwrite($out, $buff);
                        }
                    } else {
                        $this->blockData = '{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}';
                    }

                    @fclose($in);
                    @fclose($out);
                } else {
                    $this->blockData = '{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}';
                }
            }

            if (empty($this->blockData)) {
                if (!$chunks || $chunk == $chunks - 1) {
                    rename("{$filePath}.part", $filePath);
                }

                $this->blockData = '{"jsonrpc" : "2.0", "result" : null, "id" : "id"}';
            }
        }
    }

    function fnc_UploadFile($parentID, $tempFile, $fileName, $fileExt, $newFileName, $filesSettings)
    {
        global $CLASSDB;

        if (file_exists($tempFile)) {
            $singleFileTypes = array("S", "SI", "SV", "SF", "MI");

            if (isset($_POST["{$fileName}_type"])) {
                $fileType = $_POST["{$fileName}_type"];
                if (in_array($fileType, $singleFileTypes)) {
                    $singleFile = 1;
                    if (strlen($fileType) > 1) {
                        $fileType = str_replace("S", "", $fileType);
                    }
                }
            }

            $fileFolder = "";
            if (in_array($fileExt, $this->fileExtensions["images"])) {
                $fileFolder = "images/";
                if (!isset($fileType)) {
                    $fileType = "I";
                }
            } elseif (in_array($fileExt, $this->fileExtensions["files"])) {
                $fileFolder = "files/";
                if (!isset($fileType)) {
                    $fileType = "F";
                }
            }
            if (!empty($fileFolder) && isset($_POST["{$fileName}_status"]) && !strcmp($_POST["{$fileName}_status"], "done")) {
                if (isset($singleFile)) {
                    $res = $CLASSDB->fetch_array($CLASSDB->query("SELECT file_id, file_src, file_type FROM {$CLASSDB->dbPrefix}files WHERE (file_type = '{$fileType}') AND (file_parent = '{$parentID}') AND (file_module = '{$filesSettings["module"]}')"));
                    if ($res) {
                        $targetDir = $_SERVER["DOCUMENT_ROOT"] . "/" . $fileFolder . $filesSettings["folder"];

                        $this->fnc_DeleteSingleFile($filesSettings, $targetDir, $res);
                    }
                }

                $filePath     = $_SERVER["DOCUMENT_ROOT"] . "/" . $fileFolder . $filesSettings["folder"];
                $originalName = isset($_POST["{$fileName}_name"]) ? $_POST["{$fileName}_name"] : "Unknown";

                while (file_exists($filePath . $newFileName . "." . $fileExt)) {
                    $newFileName = $newFileName . "-" . $this->fnc_TepCreateRandomValue(6, "digits");
                }

                $newFileName .= "." . $fileExt;

                copy($tempFile, $filePath . $newFileName);

                if (in_array($fileExt, $this->fileExtensions["images"])) {
                    foreach ($filesSettings["thumbs"][$fileType] as $key => $imgData) {
                        $folder = $imgData["folder"] . "/";

                        list($newWidth, $newHeight) = $this->fnc_GetThumbSize($imgData["width"], $imgData["height"], $filePath . $newFileName);
                        $this->fnc_CreateThumb($filePath, $newFileName, $fileExt, $newWidth, $newHeight, $folder);
                        chmod($filePath . $folder . $newFileName, 0766);
                    }
                }

                unlink($tempFile);

                $maxPosition = $CLASSDB->fetch_array($CLASSDB->query("SELECT MAX(file_position) AS position FROM {$CLASSDB->dbPrefix}files WHERE (file_parent = '{$parentID}') AND (file_type = '{$fileType}') AND (file_module = '{$filesSettings["module"]}')"));
                $position    = $maxPosition["position"] + 1;

                $CLASSDB->query("INSERT INTO {$CLASSDB->dbPrefix}files (file_parent, file_original_name, file_src, file_position, file_type, file_module) VALUES ('{$parentID}', '{$originalName}', '{$newFileName}', '{$position}', '{$fileType}', '{$filesSettings["module"]}')");
            }
        }
    }

    function fnc_GetThumbSize($widthNeeded, $heightNeeded, $file)
    {
        list($width, $height) = getimagesize($file);
        if ($width > $height) {
            if ($widthNeeded && $width > $widthNeeded) {
                $newWidth  = $widthNeeded;
                $newHeight = intval($height * ($newWidth / $width));
            } else {
                $newWidth  = $width;
                $newHeight = $height;
            }

            if ($heightNeeded && $newHeight > $heightNeeded) {
                $newHeight = $heightNeeded;
                $newWidth  = intval($width * ($newHeight / $height));
            }
        } else {
            if ($heightNeeded && $height > $heightNeeded) {
                $newHeight = $heightNeeded;
                $newWidth  = intval($width * ($newHeight / $height));
            } else {
                $newWidth  = $width;
                $newHeight = $height;
            }

            if ($widthNeeded && $newWidth > $widthNeeded) {
                $newWidth  = $widthNeeded;
                $newHeight = intval($height * ($newWidth / $width));
            }
        }

        return array($newWidth, $newHeight);
    }

    function fnc_CreateThumb($path, $fileName, $fileExt, $thumb_w, $thumb_h, $folder)
    {
        if (!is_dir($path . $folder)) {
            mkdir($path . $folder);
            chmod($path . $folder, 0777);
        }

        $fileExt = strtolower($fileExt);
        if (preg_match("/jpg|jpeg/", $fileExt)) {
            $copyExt = "jpeg";
        } elseif (preg_match("/gif/", $fileExt)) {
            $copyExt = "gif";
        } elseif (preg_match("/png/", $fileExt)) {
            $copyExt = "png";
        }

        if (isset($copyExt)) {
            $func    = "imagecreatefrom" . $copyExt;
            $src_img = $func($path . $fileName);

            $old_x = imageSX($src_img);
            $old_y = imageSY($src_img);

            $dst_img = ImageCreateTrueColor($thumb_w, $thumb_h);
            $quality = 100;

            if (!strcmp($copyExt, "png")) {
                imagealphablending($dst_img, false);
                $colorTransparent = imagecolorallocatealpha($dst_img, 0, 0, 0, 127);
                imagefill($dst_img, 0, 0, $colorTransparent);
                imagesavealpha($dst_img, true);
                $quality = 9;
            } elseif (!strcmp($copyExt, "gif")) {
                $trnprtIndx = imagecolortransparent($src_img);
                if ($trnprtIndx >= 0) {
                    $trnprtColor = imagecolorsforindex($src_img, $trnprtIndx);
                    $trnprtIndx  = imagecolorallocate($dst_img, $trnprtColor['red'], $trnprtColor['green'], $trnprtColor['blue']);
                    imagefill($dst_img, 0, 0, $trnprtIndx);
                    imagecolortransparent($dst_img, $trnprtIndx);
                }
            }

            imagecopyresampled($dst_img, $src_img, 0, 0, 0, 0, $thumb_w, $thumb_h, $old_x, $old_y);

            $func = "image" . $copyExt;
            $func($dst_img, $path . $folder . $fileName, $quality);

            imagedestroy($dst_img);
            imagedestroy($src_img);
        }
    }

    function fnc_GetRecordUrl($var, $tblName, $tblID, $itemID)
    {
        global $CLASSDB;

        $url = isset($_POST[$var]) && !empty($_POST[$var]) ? preg_replace("/\s+/", "-", trim(strtolower(preg_replace("/[^0-9a-zA-Z]/", " ", $_POST[$var])))) : $this->fnc_TepCreateRandomValue(24);

        $check = $CLASSDB->fetch_array($CLASSDB->query("SELECT * FROM {$tblName} WHERE ({$tblID} <> '{$itemID}') AND ({$var} = '$url')"));
        if ($check) {
            $url = $url . "-" . $itemID;
        }

        return $url;
    }

    function fnc_Redirect()
    {
        $this->fnc_CleanURL("action");
        if (!empty($this->request["action"])) {
            $this->url = str_replace("redirect", $this->request["action"], $this->url);
        }

        header("Location: ?" . $this->url);
    }

    function fnc_PrepareURL($url)
    {
        return preg_replace("/\s+/", "-", trim(strtolower(preg_replace("/[^0-9a-zA-Z]/", " ", $url))));
    }

    function fnc_AddHeader($value)
    {
        $this->addHeader .= $value;
    }

    function fnc_AddRelativeJavascript($relativePath)
    {
        global $CLASSTPL;
        $this->addHeader .= '<script type="text/javascript" src="' . $CLASSTPL->path. $relativePath . '"></script>';
    }

    function fnc_AddRelativeStylesheet($relativePath)
    {
        global $CLASSTPL;
        $this->addHeader .= '<link rel="stylesheet" type="text/css" href="' . $CLASSTPL->path . $relativePath . '">';
    }

    function fnc_AddSourceJavascript($source)
    {
        $this->addHeader .= '<script type="text/javascript">' . $source . '</script>';
    }

    function fnc_GetPager($total)
    {
        if ($total) {
            $totalPages = $total / ($this->pager["limit"] * $this->pager["items"]);
            if (is_float($totalPages)) {
                $totalPages = intval(++ $totalPages);
            }
            if ($this->pager["page"] > $totalPages || $this->pager["page"] < 1) {
                $this->pager["page"] = 1;
            }

            $this->pager["total"] = $totalPages;

            if (!$this->jRequest) {
                $this->fnc_AddHeader('<link href="' . $this->path . 'css/pager.css" rel="stylesheet" type="text/css">');

                $temp = $this->fnc_Template("{$this->path}tpl/pager");
                eval("\$pager = \"$temp\";");

                $this->pager["pager"] = $pager;
            }
        }
    }

    function fnc_CleanURL($value)
    {
        $this->url = preg_replace("/($value)=([^&\?]*)(&*)/", "", $this->url);
        $last      = $this->url[strlen($this->url) - 1];

        if ($last == "&") {
            $this->url = substr($this->url,0,-1);
        }
    }

    function fnc_Convert_bin2hex($str)
    {
        $hex = "";
        $i   = 0;
        do {
            $hex .= dechex(ord($str{$i}) + 3);
            $i ++;
        } while ($i < strlen($str));

        return $hex;
    }

    function fnc_Convert_hex2bin($str)
    {
        $bin      = "";
        $oddCount = 1;
        $i        = 0;

        do {
            if (!($oddCount % 2)) {
                $bin .= chr(hexdec($str{$i} . $str{($i + 1)}) - 3);
            }

            $i += 2;
            $oddCount ++;
        } while ($i < strlen($str));

        return $bin;
    }

    function fnc_EncryptPassword($realPassword)
    {
        $newPassword = "";
        $realCount   = $codeCount = 0;

        $passLength = strlen($realPassword) * 2;
        $codeWord   = $this->fnc_TepCreateRandomValue(strlen($realPassword));

        for ($i = 1; $i <= $passLength; $i ++) {
            if (!($i % 2)) {
                $newPassword .= $realPassword[$realCount];
                $realCount ++;
            } else {
                $newPassword .= $codeWord[$codeCount];
                $codeCount ++;
            }
        }

        return $this->fnc_Convert_bin2hex($newPassword);
    }

    function fnc_TepCreateRandomValue($length, $type = 'mixed')
    {
        if (($type != 'mixed') && ($type != 'chars') && ($type != 'digits')) {
            return false;
        }

        $rand_value = '';
        while (strlen($rand_value) < $length) {
            $char = ($type == 'digits') ? $this->fnc_TepRand(0, 9) : chr($this->fnc_TepRand(0, 255));

            if ($type == 'mixed') {
                if (preg_match('/^[a-z0-9]$/', $char)) {
                    $rand_value .= $char;
                }
            } elseif ($type == 'chars') {
                if (preg_match('/^[a-z]$/', $char)) {
                    $rand_value .= $char;
                }
            } elseif ($type == 'digits') {
                if (preg_match('/^[0-9]$/', $char)) {
                    $rand_value .= $char;
                }
            }
        }

        return $rand_value;
    }

    function fnc_TepRand($min = null, $max = null)
    {
        mt_srand((double) microtime() * 1000000);

        if (isset($min) && isset($max)) {
            return ($min >= $max) ? $min : mt_rand($min, $max);
        } else {
            return mt_rand();
        }
    }

    function fnc_Template($fname)
    {
        $ret = file_get_contents("{$fname}.tpl");
        $ret = str_replace("\"", "\\\"", $ret);

        return $ret;
    }

    function fnc_Display()
    {
        global $CLASSDB;

        if (!$this->jRequest) {
            if ($this->adminPermission == "A") {
                $menu = $this->fnc_GetSubMenu();
            }

            foreach ($this->leftMenu as $key => $value) {
                $key  = str_replace("-", "_", $key);
                $$key = $value ? "S" : "";
            }

            $tempBlock = $this->fnc_Template($this->path . "tpl/menu-" . $this->adminPermission);
            eval("\$leftMenu = \"$tempBlock\";");

            $date = date("F j, Y");

            $tempBlock = $this->fnc_Template($this->path . "tpl/container");
            eval("echo \"$tempBlock\";");
        } else {
            echo $this->blockData;
        }

        $CLASSDB->close_db();
    }

}