<?php

try {
    require_once(dirname(__FILE__) . '/application.php');
    require_once(dirname(__FILE__) . '/setup.php');
    require_once(dirname(__FILE__) . '/lib/export.php');
    $tplPath = dirname(__FILE__) . "/tpl/export.html";

    @set_time_limit(0);

    class Surfacer_Export extends Surfacer
    {
        public function buildSurface(&$Tpl, $root)
        {
            $DB = DB::singleton(dsn());
            $SQL = SQL::newSelect('blog');
            $all = $DB->query($SQL->get(dsn()), 'all');

            foreach ($all as $row) {
                $vars = [
                    'bid' => $row['blog_id'],
                    'name' => $row['blog_name'],
                    'code' => $row['blog_code'],
                    'parent' => $row['blog_parent'],
                ];
                if (intval($row['blog_id']) === intval($this->Post->get('bid'))) {
                    $vars += ['checked' => ' checked="checked"'];
                }
                $Tpl->add(['blog:loop', $root], $vars);
            }
        }

        public function validate()
        {
            if ($this->Post->isNull('bid')) {
                $this->Error['blog_select'] = true;
            } else {
                $DB = DB::singleton(dsn());
                $SQL = SQL::newSelect('blog');
                $SQL->addWhereOpr('blog_id', $this->Post->get('bid'));
                if (!$DB->query($SQL->get(dsn()), 'exec')) {
                    $this->Error['blog_exist'] = true;
                }
            }

            $path = ROOT_DIR . $this->Post->get('path', SETUP_DIR);
            if (Storage::isDirectory($path)) {
                if (PHP_OS === 'WIN32' || PHP_OS === 'WINNT') {
                    if (!Storage::isReadable($path) || !Storage::isWritable($path)) {
                        $this->Error['permission'] = true;
                    }
                } else {
                    if (!Storage::isReadable($path) || !Storage::isWritable($path) || !Storage::isExecutable($path)) {
                        $this->Error['permission'] = true;
                    }
                }
            } else {
                $this->Error['directory'] = true;
            }

            if ($this->Post->isNull('name')) {
                $this->Error['name_input'] = true;
            } else {
                $name = $this->Post->get('name');
                if (preg_match('@[^\w\d\-\.]@', $name)) {
                    $this->Error['name_valid'] = true;
                }
            }

            $this->detectStep();
        }

        public function business()
        {
            @set_time_limit(0);
            ini_set('memory_limit', '1G');

            $tables = [
                'category', 'column', 'config', 'comment', 'config_set',
                'dashboard', 'entry', 'field', 'form', 'fulltext',
                'media', 'media_tag', 'geo', 'entry_sub_category',
                'module', 'rule', 'tag', 'trackback', 'schedule', 'layout_grid',
            ];

            $bid = $this->Post->get('bid');
            $name = $this->Post->get('name');
            $sep = $this->Post->get('marker');

            $Export = new Export($bid, $tables, $sep);
            $yaml = $Export->getYaml();

            if ($this->Post->get('ext') === 'zip' && !class_exists('ZipArchive')) {
                $this->Error['zip_archive'] = true;
                $this->detectStep();
                return;
            }

            $tmp = "$name/";
            /**
             * create YAML
             */
            Storage::makeDirectory($tmp);
            if (Storage::exists($tmp)) {
                Storage::put($tmp . $name . '.yaml', $yaml);
            }

            /**
             * archives & themes temporary copy for exportable
             */
            $array = $Export->getArray();
            if (
                1 &&
                ($this->Post->get('ext') === 'zip' || $this->Post->get('ext') === 'gzip') &&
                (!empty($array) && is_array($array))
            ) {
                $tmpThm = "$name/themes/";
                Storage::makeDirectory($tmpThm);
                if (Storage::exists($tmpThm)) {

                    /**
                     * detected Using Theme
                     */
                    foreach ($array['config'] as $conf) {
                        if ($conf['config_key'] == 'theme') {
                            $themeName = $conf['config_value'];
                            $themePath = ROOT_DIR . THEMES_DIR . $themeName . '/';
                            $themeTmp = $tmpThm . $themeName . '/';

                            $from = SetupCommon::fixPathSeparator($themePath);
                            $to = SetupCommon::fixPathSeparator($themeTmp);

                            Storage::makeDirectory($to);

                            if (Storage::exists($from)) {
                                Storage::copyDirectory($from, $to);
                                Storage::copy($from, $to);
                            }
                        }
                    }
                }

                $tmpArc = "$name/archives/";
                Storage::makeDirectory($tmpArc);
                if (Storage::exists($tmpArc)) {
                    /**
                     * detected Blog Archives
                     */
                    $archivePath = ROOT_DIR . ARCHIVES_DIR . sprintf("%03d", $bid) . '/';
                    if (Storage::exists($archivePath)) {
                        $archiveTmp = $tmpArc . sprintf("%03d", $bid) . '/';

                        $from = SetupCommon::fixPathSeparator($archivePath);
                        $to = SetupCommon::fixPathSeparator($archiveTmp);

                        Storage::makeDirectory($to);

                        if (Storage::exists($from)) {
                            Storage::copyDirectory($from, $to);
                            Storage::copy($from, $to);
                        }
                    }
                }
            }

            /**
             * compose zip
             */
            $distPath = '';
            $fileName = '';
            if (Storage::exists($tmp)) {
                if ($this->Post->get('ext') === 'zip' && version_compare(PHP_VERSION, '5.0.0', '>=')) {
                    $distPath = $name . '.zip';
                    $fileName = $name . '.zip';
                    Storage::compress($tmp, $distPath);
                    Storage::removeDirectory($tmp);
                } elseif ($this->Post->get('ext') === 'gzip') {
                    $distPath = $name . '.tar.gz';
                    $fileName = $name . '.tar.gz';
                    exec("tar cvf $distPath $tmp");
                    Storage::removeDirectory($tmp);
                } elseif ($this->Post->get('ext') === 'yaml') {
                    $distPath = $tmp . $name . '.yaml';
                    $fileName = $name . '.yaml';
                }
            }

            /**
             * download
             */
            if ($distPath !== '' && $fileName !== '') {
                Common::download($distPath, $fileName, false, true);
            }
        }
    }

    new Surfacer_Export($tplPath);

    App::checkException();
} catch (Exception $e) {
    App::showError($e);
}
