<?php

    require('../../../config.php');
    require_once($CFG->libdir.'/filelib.php');
    require_once($CFG->dirroot.'/blog/lib.php');
    require_once('exportlib.php');

// （注意）ユーザ情報を完全にデータベース(mdl_user)から抹消してしまった場合はエクスポートできません．
function convert_blog($user, $conf)
{
    global $CFG;

    $datafolder = $conf->pd->unique.'/blogdata';

    $blogentries = array();
    $sql = 'SELECT id,subject,attachment,created,lastmodified'
            . ' FROM '. $CFG->prefix.'post'
            . ' where (userid = '.$user->id.')'
            . ' order by created '. ($conf->descorder ? 'desc' : 'asc');
    if (!($blogentries = fs_get_records_sql($sql))) {
        echo get_string('ErrNoBlogEntries', 'fs_moodle').'<br />';
        return false;
    }

    // 前処理
    $single_main = $table_main = $text_main = $movable_main = false;
    $headertitle = get_string('blogexport','fs_moodle').':'.fullname($user);
    // 単一ページ（HTML）
    if ($conf->singlehtml) {
        $single_main = new single_format($conf->pd->shtmlroot, $conf->indexfname, 'single');
        if ($single_main->error) return false;
        if (!($single_main->output_header($user, $headertitle))) return false;
    }
    // 表形式（HTML）
    if ($conf->tablehtml) {
        $table_main  = new table_format($conf->pd->thtmlroot,  $conf->indexfname, 'table');
        if ($table_main->error) return false;
        if (!($table_main ->output_header($user, $headertitle))) return false;
        $table_main->start_main_table();
    }
    // テキストデータ
    if ($conf->textdata) {
        $textdata_main = new textdata_format( $conf->pd->textroot, 'entrylist.txt', 'textdata');
        if ($textdata_main->error) return false;
        if (!($textdata_main->output_header($headertitle))) return false;
    }

    $conf->cnt = 0;
    foreach ($blogentries as $blogentry) {
       if ($conf->enablestart and $blogentry->created < $conf->starttime) continue;
       if ($conf->enableend   and $blogentry->created > $conf->endtime)   continue;
        $conf->cnt++;
        echo "($conf->cnt)&nbsp;".userdate($blogentry->created).'->';
        // エントリの読み出し
        $blogdata = fs_get_record('post', 'id', $blogentry->id);
        if (!$blogdata) {
            echo '&nbsp;NG <br />';
            continue;
        }
        // シングル型のエントリの追記
        if ($single_main) {
            if (!($single_main->output_data($single_main->generate_html_single_entry($blogdata, $conf)))) {
                echo '&nbsp;NG <br />';
                continue;
            }
        }
        // テーブル型の出力
        if ($table_main) {
            $subfolder = $conf->idnumber ? $blogentry->id : $conf->cnt;
            $table_sub = new single_format($conf->pd->thtmlroot.'/'.$subfolder, $conf->indexfname, 'table');
            if ($table_sub->error) {
                echo '&nbsp;NG <br />';
                continue;
            }
            if (!($table_sub->output_header($user, $headertitle))) {
                echo '&nbsp;NG <br />';
                continue;
            }
            if (!($table_sub->output_data($table_sub->generate_html_single_entry($blogdata, $conf)))) {
                echo '&nbsp;NG <br />';
                continue;
            }
            $table_sub->output_footer();
            $subject->url  = $subfolder.'/'.$conf->indexfname;
            $subject->text = $blogdata->subject;
            $datestr       = userdate($blogdata->created);
            if (!($table_main->add_row($subject, $datestr, $conf))) {
                echo '&nbsp;NG <br />';
                continue;
            }
        }
        // テキストデータ型の出力
        if ($textdata_main) {
            $subfolder = $conf->idnumber ? $blogentry->id : $conf->cnt;
            $textdata_sub = new textdata_format($conf->pd->textroot.'/'.$subfolder, 'entry.txt', 'textdata');
            if ($textdata_sub->error) {
                echo '&nbsp;NG <br />';
                continue;
            }
            if (!($textdata_sub->output_header(''))) {
                echo '&nbsp;NG <br />';
                continue;
            }
            if (!($textdata_sub->output_data($textdata_sub->generate_textdata_single_entry($blogdata, $conf)))) {
                echo '&nbsp;NG <br />';
                continue;
            }
            $textdata_sub->output_footer();
            $subject->url  = $subfolder.'/entry.txt';
            $subject->text = $blogdata->subject;
            $datestr       = userdate($blogdata->created);
            if (!($textdata_main->add_row($subject, $datestr))) {
                echo '&nbsp;NG <br />';
                continue;
            }
        }

        echo '&nbsp;OK <br />';
    }
    // 後処理
    if ($single_main) {
        $single_main->output_footer();
    }
    if ($table_main) {
        $table_main->end_main_table();
        $table_main ->output_footer();
    }
    if ($text_main) {
        $textdata_main->output_footer();
    }

    return true;
}

//----------------------------

    require_login();

    $userid     = required_param('userid', PARAM_INT);
    $exportconf->singlehtml  = optional_param('singlehtml',  '1', PARAM_BOOL);
    $exportconf->tablehtml   = optional_param('tablehtml',   '1', PARAM_BOOL);
    $exportconf->textdata    = optional_param('textdata',    '1', PARAM_BOOL);
//  $exportconf->movabletype = optional_param('movabletype', '1', PARAM_BOOL);
    $exportconf->descorder   = optional_param('descorder',   '1', PARAM_BOOL);
    $exportconf->idnumber    = optional_param('idnumber',    '1', PARAM_BOOL);
    $exportconf->attfolder   = optional_param('attfolder',   '0', PARAM_BOOL);
    $exportconf->enablestart = optional_param('enablestart', '0', PARAM_BOOL);
    $exportconf->enableend   = optional_param('enableend',   '0', PARAM_BOOL);
    $startday    = optional_param('startday', '0', PARAM_INT);
    $startmon    = optional_param('startmon', '0', PARAM_INT);
    $startyr     = optional_param('startyr',  '0', PARAM_INT);
    $endday      = optional_param('endday',   '0', PARAM_INT);
    $endmon      = optional_param('endmon',   '0', PARAM_INT);
    $endyr       = optional_param('endyr',    '0', PARAM_INT);
    $exportconf->starttime = make_timestamp($startyr, $startmon, $startday,  0,  0,  0);
    $exportconf->endtime   = make_timestamp($endyr,   $endmon,   $endday,   23, 59, 59);
    $exportconf->target_blank = optional_param('target_blank', '0',          PARAM_BOOL);  // 表形式(HTML)のみ有効
    $exportconf->indexfname   = optional_param('indexfname',   'index.html', PARAM_TEXT);

    if (!fs_function_enable('FS_ENABLE_BLOGEXPORT')) {
        error('Blog Export function is not enabled!');
    }
    require_login();
    // 権限のチェック
    if (!can_export_blog($userid)) {
        print_error('youcannotexporttheseblogs', 'fs_moodle');
    }

    $downloadable = false;  // フラグ
    if (!$user = fs_get_record('user', 'id', $userid)) {
       error('Wrong user id');
    }
    // 作業用フォルダの作成
    echo get_string('generatetmpfolder', 'fs_moodle').'<br />';
    if (($exportconf->pd = generate_temp_folder($exportconf))) {
        $tempfolder = $exportconf->pd->unique;
        // blogのエクスポート
        echo get_string('blogconverting', 'fs_moodle').'<br />';
        if (convert_blog($user, $exportconf)) {
            echo get_string('convertingblogisfinished', 'fs_moodle').'<br />'; 
            // アーカイブの作成
            echo get_string('startgeneratezipfile', 'fs_moodle').'<br />';
            $sjiszipflag = false;
            $files = array();
            $zippath = $tempfolder.'/blogdata.zip';
            $files[] = $tempfolder.'/blogdata';
            if (!zip_files($files, $zippath, $sjiszipflag)) {
                error_log("Error : Cannot create zip file");
                fulldelete($tempfolder);
                exit;
            }        
            echo get_string('generatingzipfileisfinished', 'fs_moodle').'<br />';

            // アーカイブの退避
            $uniqid = md5(uniqid(rand(), true));
            $temppath = "{$CFG->dataroot}/temp";
            fs_rename($zippath, $temppath."/{$uniqid}.zip");
            $downloadable = true;
        }
        // 作業用フォルダの削除
        echo get_string('deletetmpfolder', 'fs_moodle').'<br />';
        fulldelete($tempfolder);

        // ダウンロード用ボタンの表示
        if ($downloadable and fs_file_exists($temppath."/{$uniqid}.zip")) {
            echo '<form method="put" action="downloadzip.php">';
            echo '<input type="hidden" name="uniqid" value="'.$uniqid.'" />';
            echo '<input type="submit" name="sendzip" value="'.get_string('downloadzipfile', 'fs_moodle').'" onClick="this.form.submit(); document.getElementById(\'sendzip\').disabled = true;"/>';
            echo '</form><br />';
        } else {
            error ("Fail to convert_blog");
        }
    }

    output_CloseWindowButton();

?>
