<?php
/**
 * 遠程發佈
 *
 * @version        $Id: makeremote_all.php 1 11:17 2010年7月19日Z tianya $
 * @package        DedeCMS.Administrator
 * @copyright      Copyright (c) 2007 - 2010, DesDev, Inc.
 * @license        http://help.dedecms.com/usersguide/license.html
 * @link           http://www.dedecms.com
 */
require_once(dirname(__FILE__)."/config.php");
CheckPurview('sys_MakeHtml');
require_once(DEDEINC."/arc.partview.class.php");

if($cfg_remote_site=='N') exit('Error:$cfg_remote_site is OFF,Check it!');

//生成必須同步服務器的列表
if(file_exists(DEDEDATA.'/config.file.inc.php'))
{
    require_once(DEDEDATA.'/config.file.inc.php');
}

if(empty($dopost)) $dopost = '';

$step = !isset($step)? 1 : $step;
$sta = !isset($sta)? 0 : $sta;
$totalnum = !isset($totalnum)? 0 : $totalnum;
$maketype = empty($maketype)? '' : $maketype;

//獲取同步狀態
function GetState($val)
{
    $color = ($val == 0)? 'red' : 'green';
    $signer = ($val == 0)? '未同步' : '已同步';
    return '<font color="'.$color.'">'.$signer.'</font>';
}

//生成遠程目錄數組
function addDir($filedir='', $description='', $dfserv=0, $state=0, $issystem=0)
{
    return array(
        'filedir' => $filedir,
        'description' => $description,
        'dfserv' => $dfserv,
        'state' => $state,
        'issystem' => $issystem
    );
}

//將配置數組生成配置內容
function makeConfig($dirarray=array())
{
    $config_str = '';
    foreach($dirarray as $k => $val)
    {
        $config_str .= '$remotefile['.$k.'] = array('."\n";
        $config_str .= '  \'filedir\'=>\''.$val['filedir']."',\n";
        $config_str .= '  \'description\'=>\''.$val['description']."',\n";
        $config_str .= '  \'dfserv\'=>'.$val['dfserv'].",\n";
        $config_str .= '  \'state\'=>'.$val['state'].",\n";
        $config_str .= '  \'issystem\'=>'.$val['issystem']."\n";
        $config_str .= ");\n";
    }
    return ($config_str == '')? '' : $config_str;
}

//遞歸獲取目錄 by:tianya
function getDirs($directory,$exempt = array('.','..','.ds_store','.svn'),&$files = array()) 
{ 
    //沒有則創建
    if(is_dir($directory) && !opendir($directory)) mkdir($directory,0777,TRUE);
    $handle = opendir($directory); 
  
    while(false !== ($resource = readdir($handle)))
    { 
        if(!in_array(strtolower($resource),$exempt)) 
        {
            //排除目錄
            if(is_dir($directory.$resource.'/'))
            { 
                array_merge($files, 
                getDirs($directory.$resource.'/',$exempt,$files)); 
            } else {
              //if(!is_file($directory.'/'.$resource))
              //{
              $files[] = $directory.'/'.$resource; 
              //}
            }
        } 
    }
    closedir($handle); 
    return $files; 
} 

function updateConfig($dirarray=array())
{
    //將其轉換為配置寫入文件
    $configfile = DEDEDATA.'/config.file.inc.php';
    $old_config = @file_get_contents($configfile);
    $config_str = makeConfig($dirarray);
    //替換配置項
    $new_config = preg_replace("/#<s_config>(.*)#<e_config>/s", "#<s_config>\n\n{$config_str}#<e_config>", $old_config);
    file_put_contents($configfile, $new_config);
}

if($dopost == '')
{

}
/*
function Updateremote()
*/
else if($dopost == 'updateremote')
{
    $dirbox = array(); // 定義一個目錄容器,確保目錄的唯一性
    //獲取所有HTML生成文件夾列表
    $query = "SELECT id,typedir,ispart FROM #@__arctype WHERE ispart <> '3'";
    $dsql->SetQuery($query);
    $dsql->Execute('al');
    $dirarray = array();

    $i = 0;
    while ($row = $dsql->GetArray("al"))
    {
        $darray = explode('/', preg_replace('/{cmspath}/', '', $row['typedir']));
        //僅獲取頂級目錄作為文件同步更新目錄
        if(!in_array($darray[1], $dirbox))
        {
            $dirarray[$i] = addDir('/'.$darray[1], '文檔HTML默認保存路', 0, 0, 1);
            $dirbox[] = $darray[1];
            $i++;
        }
    }
    //系統附件存放目錄
    $dirarray[$i++] = addDir($cfg_medias_dir, '圖片/上傳文件默認路徑', 0, 0, 1);
    //專題目錄
    $dirarray[$i++] = addDir('/special', '專題目錄', 0, 0, 1);
    //data/js目錄
    $dirarray[$i++] = addDir('/data/js', '生成js目錄', 0, 0, 1);
    //$remotefile = array();
    //把非系統目錄的內容提取出來
    foreach ($remotefile as $key => $value)
    {
        //處理用戶自定義配置
        if($value['issystem'] == 0)
        {
            $dirarray[$i++] = addDir($value['filedir'], $value['description'],
                                     $value['dfserv'], $value['state'], $value['issystem']);
        }
    }
    
    updateConfig($dirarray);
    
    ShowMsg("成功更新同步目錄,請重新對目錄進行同步操作!","makeremote_all.php");
    exit;
}
/*
function Make()&MakeAll()
*/
else if($dopost == 'make')
{
    if($step == 1)
    {
        if($maketype == 'makeall')
        {
            //如果更新所有,則需要重新組合$Iterm
            foreach($remotefile as $key => $val)
            {
                $Iterm[] = $val['filedir'];
            }
        } else {
            //初始化配置
            $Iterm = !isset($Iterm)? array(): $Iterm;
        }

        $serviterm = !isset($serviterm)? array(): $serviterm;
        $cacheMakeFile = DEDEDATA.'/cache/filelist.inc.php';
        $dirlist = $alllist = $updir = array();
        $dirindex = 0;//目錄統一索引
        
        //採用比較人性化的更新方式進行提示更新
        //初始化本地文件夾底層的子集目錄
        
        if(count($Iterm) > 0)
        {
            //獲取遠程文件(夾)列表
            foreach($Iterm as $key => $val)
            {
                $config = $serviterm[$key];
                if(is_array($dirlist = getDirs(DEDEROOT.$val)))
                {
                    foreach($dirlist as $k => $v)
                    {
                        $alllist[] = $v.'|'.$config;
                        if(!in_array($val, array_values($updir))) $updir[] = $val;
                    }
                }
            }
            //遍歷文件夾列表,如果存在子集文件夾大於3的則需要進行細分
            //將列表寫入緩存
            $cachestr = "<?php \n  global \$dirlist,\$upremote;\n  \$dirlist=array();\n";
            foreach($alllist as $key => $val)
            {
                list($filename,$fileconfig) = explode('|', $val); 
                if(is_dir($filename))
                {
                    $deepDir = getDirs($filename);
                    $dd = 0;
                    //先遍歷一遍確定子集文件夾數目
                    foreach($deepDir as $k => $v)
                    {
                        if(is_dir($v)) $dd++;
                    }
                    if($dd > 3)
                    {
                        //如果自己文件夾數目大於3則
                        foreach($deepDir as $k => $v)
                        {
                            $v .= '|'.$fileconfig;
                            $cachestr .= "  \$dirlist['$dirindex']='$v';\n";
                            $dirindex++;
                        }
                    }else{
                        $cachestr .= "  \$dirlist['$dirindex']='$val';\n";
                        $dirindex++;
                    }
                }
            }
            
            foreach($updir as $key => $val)
            {
                $cachestr .= "  \$upremote['$key']='$val';\n";
            }
            $cachestr .= "?>";
            file_put_contents($cacheMakeFile, $cachestr);
            $tnum = count($alllist);
            ShowMsg("成功獲取遠程列表,下面進行文件遠程發佈!","makeremote_all.php?dopost=make&step=2&sta=1&totalnum=$tnum");
            exit;
        } else {
            echo '您沒有選擇,請先選擇再點擊更新!';
        }
        exit;    
    } elseif ($step == 2)
    {
        if(file_exists(DEDEDATA.'/cache/filelist.inc.php'))
        {
            require_once(DEDEDATA.'/cache/filelist.inc.php');
        }
        if(is_array($dirlist))
        {
            if($sta > 0 && $sta < $totalnum)
            {
                list($dirname, $ftpconfig) = explode('|', $dirlist[$sta-1]); 
                list($servurl, $servuser, $servpwd) = explode(',', $ftpconfig);
                $config=array( 'hostname' => $servurl, 'username' => $servuser,
                               'password' => $servpwd,'debug' => 'TRUE');
                if($ftp->connect($config))
                {
                    //var_dump(is_dir($dirname));exit;
                    if(is_dir($dirname))
                    {
                        //如果是文件目錄
                        $remotedir = str_replace(DEDEROOT, '', $dirname).'/';
                        $localdir = '..'.$remotedir.'/';
                        $ftp->rmkdir($remotedir);
                        if( $ftp->mirror($localdir, $remotedir))
                        {
                            $sta++;
                            ShowMsg("成功同步文件夾$remotedir,進入下一個任務","makeremote_all.php?dopost=make&step=2&sta={$sta}&totalnum=$totalnum");
                            exit;
                        }
                    } else {
                        $remotefile = str_replace(DEDEROOT, '', $dirname);
                        $localfile = '..'.$remotefile;
                        //創建遠程文件夾
                        $remotedir = preg_replace('/[^\/]*\.(\w){0,}/', '', $remotefile);
                        
                        //如果是文件則需要智能處理
                        $remotebox = array();
                        $ftp->rmkdir($remotedir);
                        foreach($dirlist as $key => $val)
                        {
                            list($filename,$fileconfig) = explode('|', $val); 
                            if(preg_replace('/[^\/]*\.(\w){0,}/', '', str_replace(DEDEROOT, '', $filename)) == $remotedir)
                            {
                                //如果這些文件都在同一目錄,則統計這些記錄的id項目
                                $remotebox[] = $key;
                            }
                        }
                        //print_r($remotebox);
                        //if(count($remotebox) > 1 && count($remotebox) < 20)
                        if(count($remotebox) > 1)
                        {
                            //如果大於1,則說明有多條記錄在同一文件夾內
                            $localdir = '..'.$remotedir;
                            if( $ftp->mirror($localdir, $remotedir))
                            {
                                $sta = end($remotebox) + 1;
                                ShowMsg("成功同步文件夾$remotedir,進入下一個任務","makeremote_all.php?dopost=make&step=2&sta={$sta}&totalnum=$totalnum");
                                exit;
                            }
                        } else {
                            if( $ftp->upload($localfile, $remotefile) )
                            {
                                $sta++;
                                ShowMsg("成功同步文件$remotefile,進入下一個任務","makeremote_all.php?dopost=make&step=2&sta={$sta}&totalnum=$totalnum");
                                exit;
                            }
                        }
                    }
                }
            } else {
                //否則成功更新完畢
                foreach($remotefile as $key => $val)
                {
                    if(in_array($val['filedir'],array_values($upremote)))
                    {
                        $remotefile[$key]['state'] = 1;
                    }
                }
                updateConfig($remotefile);
                @unlink(DEDEDATA.'/cache/filelist.inc.php');
                echo '全部同步完畢!';exit;
            }
        } else {
            exit('Error:None remote cache file exist!');
        }
        exit;
    }
}
include DedeInclude('templets/makeremote_all.htm');