<?php
/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
class EditorController extends Controller {
    public function __construct() {
        parent::__construct();
        $this->ObjCommon->askPrivilege('editor/design/');
    }
    public function designAction() {
        $resThemes = $this->listThemes();
        $this->ObjView->assign('currentTheme', __THEME);
        $this->ObjView->assign('resThemes', $resThemes[0]);
        $this->ObjView->display('DesignMode.tpl');
    }
    private function listThemes() {
        $globalUrl   = $this->getSettingValue('site_settings', 'global_http_url');
        $dirCoreView = __CORE_PATH . "/views/" . __DIR_FRONTEND;
        $dirview     = scandir($dirCoreView);
        $exceptDir   = array(
            ".",
            "..",
            ".gitignore"
        );
        $imagePath   = $globalUrl . "/application/core/views/" . __DIR_FRONTEND . "/";
        $xmlPath     = "theme-config/";
        $listThemes  = array();
        foreach ($dirview as $themeDir) {
            if (!in_array($themeDir, $exceptDir)) {
                $themeConfigXml = $dirCoreView . "/" . $themeDir . "/" . $xmlPath . "/template.xml";
                $xml            = (array) simplexml_load_file($themeConfigXml);
                if (__THEME == $xml['@attributes']['key']) {
                    $currentThemeImage = $imagePath . $themeDir . "/theme-config/theme/thumb/" . $xml['@attributes']['image'];
                    array_push($listThemes, array(
                        'themekey' => $xml['@attributes']['key'],
                        'themeName' => $xml['@attributes']['name'],
                        'imagePreview' => $imagePath . $themeDir . "/theme-config/theme/" . $xml['@attributes']['image'],
                        'imageThumb' => $imagePath . $themeDir . "/theme-config/theme/thumb/" . $xml['@attributes']['image'],
                        'activeStatus' => 'Yes'
                    ));
                } else {
                    array_push($listThemes, array(
                        'themekey' => $xml['@attributes']['key'],
                        'themeName' => $xml['@attributes']['name'],
                        'imagePreview' => $imagePath . $themeDir . "/theme-config/theme/" . $xml['@attributes']['image'],
                        'imageThumb' => $imagePath . $themeDir . "/theme-config/theme/thumb/" . $xml['@attributes']['image'],
                        'activeStatus' => 'No'
                    ));
                }
            }
        }
        return array(
            $listThemes,
            $currentThemeImage
        );
    }
    public function templateAction() {
        $objEditor           = new EditorModel();
        $fullFiles           = array();
        $filtoeditDefault    = '';
        $siteUrl             = $this->getSettingValue('site_settings', 'global_http_url');
        //template files path
        $dirTEMP             = __CORE_FRONTEND_VIEWS_PATH;
        //public path
        $dirPublicPath       = __CORE_PUBLIC_FRONTEND_PATH;
        $dirPublicCommonPath = __CORE_PUBLIC_COMMON_FRONTEND_PATH;
        //sort array
        $tsortkey            = ($this->getRequestValue("tsort") ? $this->getRequestValue("tsort") : 'a');
        $ssortkey            = ($this->getRequestValue("ssort") ? $this->getRequestValue("ssort") : 'a');
        $jsortkey            = ($this->getRequestValue("jsort") ? $this->getRequestValue("jsort") : 'a');
        $isortkey            = ($this->getRequestValue("isort") ? $this->getRequestValue("isort") : 'a');
        $lsortkey            = ($this->getRequestValue("lsort") ? $this->getRequestValue("lsort") : 'a');
        $date_format         = $this->getSettingValue('site_settings', 'date_format');
        $exclude_list        = array(
            "theme-config"
        );
        $fullFilesTPL        = $this->directoryToArraytype($dirTEMP, false, true, $exclude_list, 'TPL', $tsortkey);
        //	echo "<pre>";print_r($_POST);	//exit;
        // for css dir
        $exclude_list        = array(
            "custom.css"
        );
        $fullFilesCSS        = $this->directoryToArraytype($dirPublicPath . '/styles', false, true, $exclude_list, 'CSS', $ssortkey);
        // exclude files for javascript dir
        $exclude_list        = array(
            "src",
            "jscolor",
            "theme"
        );
        $fullFilesJS         = $this->directoryToArraytype($dirPublicCommonPath . '/javascript', false, true, $exclude_list, 'JS', $jsortkey);
        //for images
        $exclude_list        = array(
            "uitheme",
            "smoothness"
        );
        $fullFilesIMAGE      = $this->directoryToArraytype($dirPublicPath . '/images', false, true, $exclude_list, 'IMAGE', $isortkey);
        //for xml language
        $exclude_list        = array(
            ".gitignore"
        );
        $fullFilesLANGUAGE   = $this->directoryToArraytype($dirPublicCommonPath . '/languages', false, true, $exclude_list, 'LANGUAGE', $lsortkey);
        $fullFiles           = array_merge($fullFilesTPL, $fullFilesCSS, $fullFilesJS, $fullFilesIMAGE, $fullFilesLANGUAGE);
        $filekey             = ($this->getRequestValue("key") != '' ? $this->getRequestValue("key") : key($fullFiles['TPL']));
        $typekey             = ($this->getRequestValue("type") != '' ? $this->getRequestValue("type") : 'TPL');
        // echo "<pre>";print_r(array_keys($fullFiles));	//exit;
        if (isset($_POST['searchSubmit'])) {
            $searchType = $_POST['typekeySearch'];
            $searchKey  = $_POST['search_' . $searchType];
            if ($searchKey != '') {
                $filekey = $this->search_array($searchKey, $fullFiles[$searchType]);
                $this->setRedirect('/editor/template/type/' . $searchType . '/key/' . $filekey . '/tsort/' . $tsortkey . '/ssort/' . $ssortkey . '/jsort/' . $jsortkey . '/isort/' . $isortkey . '/lsort/' . $lsortkey . '/');
            } else {
                $this->setRedirect();
            }
        }
        //current content
        $filepathactive = $fullFiles[$typekey][$filekey]['path'];
        $filenameactive = $fullFiles[$typekey][$filekey]['filename']; // $filekey ;
        $previewactive  = isset($fullFiles[$typekey][$filekey]['previewpath']) ? $fullFiles[$typekey][$filekey]['previewpath'] : ''; // $filekey ;
        $defaultfile    = $filepathactive . $filenameactive;
        //old content
        $viewold        = $this->getRequestValue("v");
        if ($viewold == 1) {
            $imagePath        = "/uploads/filebackup/";
            $filcontent       = $objEditor->getOldFile($filenameactive, $filepathactive);
            $filtoeditDefault = $filcontent['filecontent'];
            if ($typekey == 'IMAGE') {
                $filtoeditDefault = $fullFiles[$typekey][$filekey]['filename'];
                if (is_file(__CORE_PUBLIC_PATH . "/uploads/filebackup/" . $filtoeditDefault)) {
                    list($width, $height, $type, $attr) = getimagesize(__CORE_PUBLIC_PATH . "/uploads/filebackup/" . $filtoeditDefault);
                    $ext = substr($filenameactive, strpos($filenameactive, ".") + 1);
                    $this->ObjView->assign("width", $width);
                    $this->ObjView->assign("height", $height);
                    $this->ObjView->assign("ext", $ext);
                } else {
                    $this->setRedirect('/editor/template/type/' . $typekey . '/key/' . $filekey . '/tsort/' . $tsortkey . '/' . '/ssort/' . $ssortkey . '/jsort/' . $jsortkey . '/isort/' . $isortkey . '/lsort/' . $lsortkey . '/');
                }
            }
        }
        if (!$filtoeditDefault) {
            if ($typekey == 'IMAGE') {
                list($width, $height, $type, $attr) = getimagesize($defaultfile);
                $ext = substr($filenameactive, strpos($filenameactive, ".") + 1);
                $this->ObjView->assign("width", $width);
                $this->ObjView->assign("height", $height);
                $this->ObjView->assign("ext", $ext);
                $filtoeditDefault = strstr($defaultfile, __DIR_PUBLIC_CORE);
                $imagePath        = strstr($filepathactive, __DIR_PUBLIC_CORE);
            } else {
                $filtoeditDefault = is_file($defaultfile) ? file_get_contents($defaultfile) : '';
            }
        }
        if ($this->ObjForm->isValid('formTemplateEditor', 'editorSubmit')) {
            $rs = $objEditor->saveChangedFile($_POST, $viewold);
            if ($rs) {
                $this->setMessage("language.msgFileUpdated", "message_success");
                $this->setRedirect('/editor/template/type/' . $typekey . '/key/' . $filekey . '/tsort/' . $tsortkey . '/ssort/' . $ssortkey . '/jsort/' . $jsortkey . '/isort/' . $isortkey . '/lsort/' . $lsortkey . '/');
            }
        }
        $this->ObjView->assign("filtoeditDefault", ($filtoeditDefault));
        $this->ObjView->assign("fileFullPath", $fullFiles);
        if ($typekey == 'IMAGE') {
            $this->ObjView->assign("imagePath", $imagePath);
        }
        $this->ObjView->assign("typekeyActive", $typekey);
        $this->ObjView->assign("filepathactive", $filepathactive);
        $this->ObjView->assign("filenameactive", $filenameactive);
        $this->ObjView->assign("filekey", $filekey);
        $this->ObjView->assign("viewold", $viewold);
        $this->ObjView->assign("ssortkey", $ssortkey);
        $this->ObjView->assign("tsortkey", $tsortkey);
        $this->ObjView->assign("jsortkey", $jsortkey);
        $this->ObjView->assign("isortkey", $isortkey);
        $this->ObjView->assign("lsortkey", $lsortkey);
        $this->ObjView->assign('siteUrl', $siteUrl);
        $this->ObjView->assign('date_format', $date_format);
        $this->ObjView->assign('previewactive', $previewactive);
        $this->ObjView->assign('fullFilesTypes', array_keys($fullFiles));
        $this->ObjView->display('TemplateEditor.tpl');
    }
    //search array for file
    private function search_array($key, $array) {
        foreach ($array as $k => $item) {
            if (in_array($key, $item))
                return $k;
        }
    }
    //get array to assigned type
    function directoryToArraytype($directory, $listDirs = false, $listFiles = true, $exclude = '', $type = '', $sortkey = '') {
        $totArrayItems = array();
        if ($directory)
            $arrayItems = $this->directoryToArray($directory, true, false, true, $exclude);
        $i = 0;
        foreach ($arrayItems as $file) {
            $fileFullPath[$i]['path']         = substr($file, 0, strripos($file, '/') + 1);
            $fileFullPath[$i]['filename']     = $filename = substr($file, strripos($file, '/') + 1);
            $fileFullPath[$i]['date']         = filemtime($file);
            $fileFullPath[$i]['modifiedDate'] = date("F d Y H:i:s", filemtime($file));
            $previewpath                      = '';
            if ($type == 'TPL') {
                $xml = simplexml_load_file(__CORE_PUBLIC_PATH . '/design/' . "templateGroup.xml");
                foreach ($xml->children() as $groups) {
                    foreach ($groups->children() as $group => $data) {
                        if (in_array($filename, explode(",", $data->filenames))) {
                            $previewpath = $data->controller . '/' . $data->action . '/';
                        }
                    }
                }
                $fileFullPath[$i]['previewpath'] = $previewpath;
            }
            if ($type == 'CSS') {
                $xml = simplexml_load_file(__CORE_PUBLIC_PATH . '/design/' . "CSSGroup.xml");
                foreach ($xml->children() as $groups) {
                    foreach ($groups->children() as $group => $data) {
                        if (in_array($filename, explode(",", $data->filenames))) {
                            $previewpath = $data->controller . '/' . $data->action . '/';
                        }
                    }
                }
                $fileFullPath[$i]['previewpath'] = $previewpath;
            }
            $i++;
        }
        if ($sortkey == '' || $sortkey == 'a' || $sortkey == 'adesc') {
            $sorter = "asc";
            if ($sortkey == 'adesc')
                $sorter = "desc";
            $fileFullPath = $this->aasort($fileFullPath, "filename", $sorter);
        }
        if ($sortkey == 'd' || $sortkey == 'ddesc') {
            $sorter = "desc";
            if ($sortkey == 'ddesc')
                $sorter = "asc";
            $fileFullPath = $this->aasort($fileFullPath, "date", $sorter);
        }
        $totArrayItems[$type] = $fileFullPath;
        return $totArrayItems;
    }
    /**
     * Get an array that represents directory tree
     * @param string $directory     Directory path
     * @param bool $recursive         Include sub directories
     * @param bool $listDirs         Include directories on listing
     * @param bool $listFiles         Include files on listing
     * @param regex $exclude         Exclude paths that matches this regex
     */
    function directoryToArray($directory, $recursive = true, $listDirs = false, $listFiles = true, $exclude = '') {
        $arrayItems    = array();
        $skipByExclude = false;
        $handle        = opendir($directory);
        if ($handle) {
            while (false !== ($file = readdir($handle))) {
                $skipByExclude = false;
                preg_match("/(^(([\.]){1,2})$|(\.(svn|git|md))|(Thumbs\.db|\.DS_STORE))$/iu", $file, $skip);
                if (is_array($exclude) and in_array($file, $exclude)) {
                    $skipByExclude = true;
                }
                if (!$skip && !$skipByExclude) {
                    if (is_dir($directory . DIRECTORY_SEPARATOR . $file)) {
                        if ($recursive) {
                            $arrayItems = array_merge($arrayItems, $this->directoryToArray($directory . DIRECTORY_SEPARATOR . $file, $recursive, $listDirs, $listFiles, $exclude));
                        }
                        if ($listDirs) {
                            $file         = $directory . DIRECTORY_SEPARATOR . $file;
                            $arrayItems[] = $file;
                        }
                    } else {
                        if ($listFiles) {
                            $file         = $directory . DIRECTORY_SEPARATOR . $file;
                            $arrayItems[] = $file;
                        }
                    }
                }
            }
            closedir($handle);
        }
        return $arrayItems;
    }
    function aasort(&$array, $key, $order) {
        $sorter = array();
        $ret    = array();
        reset($array);
        foreach ($array as $ii => $va) {
            $sorter[$ii] = isset($va[$key]) ? $va[$key] : '';
        }
        if ($order == "asc")
            asort($sorter);
        else
            arsort($sorter);
        foreach ($sorter as $ii => $va) {
            $ret[$ii] = $array[$ii];
        }
        $array = $ret;
        return $array;
    }
    public function ajaxFileAutocompleteAction() {
        $fullFiles           = array();
        //template files path
        $dirTEMP             = __CORE_FRONTEND_VIEWS_PATH;
        //public path
        $dirPublicPath       = __CORE_PUBLIC_FRONTEND_PATH;
        $dirPublicCommonPath = __CORE_PUBLIC_COMMON_FRONTEND_PATH;
        $typekey             = ($this->getRequestValue("type") != '' ? $this->getRequestValue("type") : 'TPL');
        if ($typekey == 'TPL') {
            $exclude_list = array(
                "theme-config"
            );
            $dir          = $dirTEMP;
        } else if ($typekey == 'CSS') {
            $exclude_list = array(
                "custom.css"
            );
            $dir          = $dirPublicPath . '/styles';
        } else if ($typekey == 'JS') {
            $exclude_list = array(
                "src",
                "jscolor",
                "theme"
            );
            $dir          = $dirPublicCommonPath . '/javascript';
        } else if ($typekey == 'IMAGE') {
            $exclude_list = array(
                "uitheme",
                "smoothness"
            );
            $dir          = $dirPublicPath . '/images';
        } else {
            $exclude_list = array(
                ".gitignore"
            );
            $dir          = $dirPublicCommonPath . '/languages';
        }
        $fullFiles = $this->directoryToArray($dir, true, false, true, $exclude_list);
        foreach ($fullFiles as $file) {
            $fileFullPath[] = substr($file, strripos($file, '/') + 1);
        }
        $fileFullPath        = $this->aasort($fileFullPath, "filename", "asc");
        $fileFullPath_unique = array_unique($fileFullPath);
        $result              = implode('*->', array_map(array(
            $this,
            'formatForJson'
        ), $fileFullPath_unique));
        $result              = $result . '**->' . $typekey;
        echo rtrim($result, '*->');
        ;
    }
    private function formatForJson($array) {
        return addslashes($array);
    }
    public function activateAction() {
        $objTheme     = new ThemeModel();
        $themeKey     = $this->getRequestValue("key");
        $globalUrl    = rtrim($this->getSettingValue('site_settings', 'global_http_url'), "/");
        $imagePath    = $globalUrl . "/application/core/views/" . __DIR_FRONTEND . "/" . $themeKey . "/theme-config/layout/";
        $themeDir     = __CORE_PATH . "/views/" . __DIR_FRONTEND . "/" . $themeKey;
        $themeConfig  = __CORE_PATH . "/views/" . __DIR_FRONTEND . "/" . $themeKey . "/theme-config/";
        $templateFile = $themeDir . "/theme-config/template.xml";
        if (isset($_POST['submitActivate'])) {
            $currentTheme = $_POST['themeKey'];
            $objTheme->activateLayout($_POST);
            $file_array = array();
            $file = fopen(__ROOT_PATH . '/system/config/config.php', 'rt') or die("can't open file");
            if ($file) {
                while (!feof($file)) {
                    $line = fgets($file);
                    if (is_string($line)) {
                        if (strpos($line, '__THEME') && !strpos($line, '$_SESSION')) {
                            $line = "define('__THEME', '" . strtolower($currentTheme) . "');\n";
                        }
                        array_push($file_array, $line);
                    }
                }
                fclose($file);
            }
            $filename = __ROOT_PATH . '/system/config/config.php';
            $file_write = fopen($filename, 'wt') or die("can't open file");
            if ($file_write) {
                fwrite($file_write, implode("", $file_array));
                fclose($file_write);
            }
            $this->setMessage("language.msgCurrentThemeUpdated", "message_success");
            $this->setRedirect('editor/activate/key/' . $currentTheme);
        }
        $resPageLayout = $objTheme->getPageLayout($themeKey);
        if (is_dir($themeDir)) {
            if (file_exists($templateFile)) {
                $xml = simplexml_load_file($templateFile);
                foreach ($xml->children() as $group) {
                    $group                              = (array) $group;
                    $groupType                          = $group['@attributes']['type'];
                    $groupTitle                         = $group['@attributes']['title'];
                    $templateArray[$groupType]['pages'] = array();
                    $templateArray[$groupType]['title'] = $groupTitle;
                    $groupPage                          = (array) $group['page'];
                    if (!empty($groupPage[0])) {
                        foreach ($group['page'] as $child) {
                            $child                     = (array) $child;
                            $tplSelected               = '';
                            $pageKeyArr                = array();
                            $pageKeyArr['key']         = $child['key'];
                            $pageKeyArr['languageKey'] = $child['languageKey'];
                            foreach ($resPageLayout as $pageLayout) {
                                if (in_array($pageKeyArr['key'], $pageLayout)) {
                                    $tplSelected = $pageLayout['tplName'];
                                }
                            }
                            $pageKeyArr['checked'] = $tplSelected;
                            $layOutKeyArr          = array();
                            $layoutArray           = (array) $child['layout'];
                            if (!empty($layoutArray[0])) {
                                foreach ($layoutArray as $key => $layout) {
                                    $layout = (array) $layout;
                                    if ($pageKeyArr['checked'] == '' && $key == 0) {
                                        $pageKeyArr['checked'] = $layout['tpl'];
                                    }
                                    array_push($layOutKeyArr, array(
                                        'name' => ucwords($layout['name']),
                                        'tpl' => $layout['tpl'],
                                        'img' => $layout['img']
                                    ));
                                }
                            } else {
                                array_push($layOutKeyArr, array(
                                    'name' => ucwords($layoutArray['name']),
                                    'tpl' => $layoutArray['tpl'],
                                    'img' => $layoutArray['img']
                                ));
                                if ($pageKeyArr['checked'] == '' && $key == 0) {
                                    $pageKeyArr['checked'] = $layoutArray['tpl'];
                                }
                            }
                            $pageKeyArr['layout'] = $layOutKeyArr;
                            array_push($templateArray[$groupType]['pages'], $pageKeyArr);
                        }
                    } else {
                        $groupPage      = (array) $group['page'];
                        $layouts        = array();
                        $pageArr['key'] = $groupPage['key'];
                        foreach ($resPageLayout as $pageLayout) {
                            if (in_array($pageArr['key'], $pageLayout)) {
                                $defaultTpl = $pageLayout['tplName'];
                            }
                        }
                        $pageArr['checked']     = $defaultTpl;
                        $pageArr['languageKey'] = $groupPage['languageKey'];
                        $layoutArray            = (array) $groupPage['layout'];
                        if (!empty($layoutArray[0])) {
                            foreach ($layoutArray as $key => $layout) {
                                $layout = (array) $layout;
                                if ($pageArr['checked'] == '' && $key == 0) {
                                    $pageArr['checked'] = $layout['tpl'];
                                }
                                array_push($layouts, array(
                                    'name' => ucwords($layout['name']),
                                    'tpl' => $layout['tpl'],
                                    'img' => $layout['img']
                                ));
                            }
                        } else {
                            array_push($layouts, array(
                                'name' => ucwords($layoutArray['name']),
                                'tpl' => $layoutArray['tpl'],
                                'img' => $layoutArray['img']
                            ));
                            $pageArr['checked'] = $layoutArray['tpl'];
                        }
                        $pageArr['layout'] = $layouts;
                        array_push($templateArray[$groupType]['pages'], $pageArr);
                    }
                }
            } else {
                echo "<h3>Info : Template file (template.xml) not found in /view/" . strtolower($themKey) . "/theme-config/</h3>";
                exit;
            }
        } else {
            echo "<h3>Info : Directory not found in /view/" . strtolower($themKey) . "/<h3>";
            exit;
        }
        //echo '<pre>'; print_r($templateArray); exit;
        $this->ObjView->assign('templateArray', $templateArray);
        $this->ObjView->assign('themeKey', $themeKey);
        $this->ObjView->assign('imagePath', $imagePath);
        $this->ObjView->display('ThemeActivation.tpl');
    }
}