/**
 * print file list worker
 *
 * @param $basedir
 * @param $dir
 * @param $type 1 = list, 2 = checksums
 * @param $mode 1 = text, 2 = html
 * @return revision-list as html-snip
 */
function _printFileList($basedir, $dir, $type = 1, $mode = 2)
{
    global $fileList;
    if (!is_dir($dir)) {
        return false;
    }
    $dirHandle = opendir($dir);
    while ($file = readdir($dirHandle)) {
        $fullpath = $dir . '/' . $file;
        if (is_dir($fullpath)) {
            if ($file[0] != '.') {
                _printFileList($basedir, $fullpath, $type, $mode);
            }
        } else {
            $stringLength = strlen($file);
            foreach ($fileList['types'] as $ftype) {
                $extLength = strlen($ftype);
                if ($stringLength > $extLength && strtolower(substr($file, -$extLength)) === $ftype) {
                    // count
                    $fileList['count'] += 1;
                    // file
                    $_file = str_replace($basedir, '', $fullpath);
                    switch ($type) {
                        default:
                        case 1:
                            // vars
                            $_size = filesize($fullpath);
                            $_rev = getSVNRevisionFromId($fullpath);
                            // size
                            $fileList['size'] += $_size;
                            // rev
                            if ($_rev != 'NoID') {
                                $intrev = intval($_rev);
                                if ($intrev > $fileList['revision']) {
                                    $fileList['revision'] = $intrev;
                                }
                            }
                            // print
                            switch ($mode) {
                                default:
                                case 1:
                                    echo $_file . ';' . $_size . ';' . $_rev . "\n";
                                    break;
                                case 2:
                                    $line = '<a href="' . _URL_SVNFILE . $_file . _URL_SVNFILE_SUFFIX . '" target="_blank">' . $_file . '</a> | ';
                                    $line .= formatHumanSize($_size) . ' | ';
                                    $line .= $_rev != 'NoID' ? '<a href="' . _URL_SVNLOG . $_rev . _URL_SVNLOG_SUFFIX . '" target="_blank">' . $_rev . '</a>' : 'NoID';
                                    $line .= '<br>';
                                    sendLine($line);
                                    break;
                            }
                            break;
                        case 2:
                            // vars
                            $_md5 = md5_file($fullpath);
                            // print
                            switch ($mode) {
                                default:
                                case 1:
                                    echo $_file . ';' . $_md5 . "\n";
                                    break;
                                case 2:
                                    sendLine($_file . " " . $_md5 . "<br>");
                                    break;
                            }
                            break;
                    }
                }
            }
        }
    }
    closedir($dirHandle);
}
/**
 * backup of flux-installation
 *
 * @param $talk : boolean if function should talk
 * @param $compression : 0 = none | 1 = gzip | 2 = bzip2
 * @return string with name of backup-archive, string with "" in error-case.
 */
function backupCreate($talk = false, $compression = 0)
{
    global $cfg, $error;
    // backup-dir
    $dirBackup = $cfg["path"] . _DIR_BACKUP;
    if (!checkDir($dirBackup)) {
        $error = "Errors when checking/creating backup-dir : " . $dirBackup;
        return "";
    }
    // files and more strings
    $backupName = "backup_" . _VERSION_THIS . "_" . date("YmdHis");
    $fileArchiveName = $backupName . ".tar";
    $tarSwitch = "-cf";
    switch ($compression) {
        case 1:
            $fileArchiveName .= ".gz";
            $tarSwitch = "-zcf";
            break;
        case 2:
            $fileArchiveName .= ".bz2";
            $tarSwitch = "-jcf";
            break;
    }
    $fileArchive = $dirBackup . '/' . $fileArchiveName;
    $fileDatabase = $dirBackup . '/database.sql';
    $fileDocroot = $dirBackup . '/docroot.tar';
    // command-strings
    $commandArchive = "cd " . $dirBackup . "; tar " . $tarSwitch . " " . $fileArchiveName . " ";
    $commandDatabase = "";
    switch ($cfg["db_type"]) {
        case "mysql":
            $commandDatabase = "mysqldump -h " . $cfg["db_host"] . " -u " . $cfg["db_user"] . " --password="******"db_pass"] . " --all -f " . $cfg["db_name"] . " > " . $fileDatabase;
            $commandArchive .= 'database.sql ';
            break;
        case "sqlite":
            $commandDatabase = "sqlite " . $cfg["db_host"] . " .dump > " . $fileDatabase;
            $commandArchive .= 'database.sql ';
            break;
    }
    $commandArchive .= 'docroot.tar';
    //$commandDocroot = "cd ".$dirBackup."; tar -cf docroot.tar ".$_SERVER['DOCUMENT_ROOT']; // with path of docroot
    $commandDocroot = "cd " . $_SERVER['DOCUMENT_ROOT'] . "; tar -cf " . $fileDocroot . " .";
    // only content of docroot
    // database-command
    if ($commandDatabase != "") {
        if ($talk) {
            sendLine('Backup of Database <em>' . $cfg["db_name"] . '</em> ...');
        }
        shell_exec($commandDatabase);
    }
    if ($talk) {
        sendLine(' <font color="green">Ok</font><br>');
    }
    // docroot-command
    if ($talk) {
        sendLine('Backup of Docroot <em>' . $_SERVER['DOCUMENT_ROOT'] . '</em> ...');
    }
    shell_exec($commandDocroot);
    if ($talk) {
        sendLine(' <font color="green">Ok</font><br>');
    }
    // create the archive
    if ($talk) {
        sendLine('Creating Archive <em>' . $fileArchiveName . '</em> ...');
    }
    shell_exec($commandArchive);
    if ($talk) {
        sendLine(' <font color="green">Ok</font><br>');
    }
    // delete temp-file(s)
    if ($talk) {
        sendLine('Deleting temp-files ...');
    }
    if ($commandDatabase != "") {
        @unlink($fileDatabase);
    }
    @unlink($fileDocroot);
    if ($talk) {
        sendLine(' <font color="green">Ok</font><br>');
    }
    // log
    if ($talk) {
        sendLine('<font color="green">Backup Complete.</font><br>');
    }
    AuditAction($cfg["constants"]["admin"], "FluxBackup Created : " . $fileArchiveName);
    return $fileArchiveName;
}
/**
 * validate Local Files
 */
function validateLocalFiles()
{
    sendLine('<h3>Validate Files</h3>');
    sendLine('<strong>Getting Checksum-list</strong>');
    // download list
    $checksumsString = "";
    @ini_set("allow_url_fopen", "1");
    @ini_set("user_agent", "torrentflux-b4rt/" . _VERSION);
    if ($urlHandle = @fopen(_SUPERADMIN_URLBASE . _FILE_CHECKSUMS_PRE . _VERSION . _FILE_CHECKSUMS_SUF, 'r')) {
        stream_set_timeout($urlHandle, 15);
        $info = stream_get_meta_data($urlHandle);
        while (!feof($urlHandle) && !$info['timed_out']) {
            $checksumsString .= @fgets($urlHandle, 8192);
            $info = stream_get_meta_data($urlHandle);
            sendLine('.');
        }
        @fclose($urlHandle);
    }
    if (empty($checksumsString)) {
        exit('error getting checksum-list from ' . _SUPERADMIN_URLBASE);
    }
    sendLine('<font color="green">done</font><br>');
    sendLine('<br><strong>Processing list</strong>');
    // remote Checksums
    $remoteChecksums = array();
    $remoteSums = explode("\n", $checksumsString);
    $remoteSums = array_map('trim', $remoteSums);
    foreach ($remoteSums as $remSum) {
        $tempAry = explode(";", $remSum);
        if (!empty($tempAry[0]) && !empty($tempAry[1])) {
            $remoteChecksums[$tempAry[0]] = $tempAry[1];
            sendLine('.');
        }
    }
    $remoteChecksumsCount = count($remoteChecksums);
    sendLine('<font color="green">done</font> (' . $remoteChecksumsCount . ')<br>');
    // local Checksums
    sendLine('<br><strong>Getting local checksums</strong>');
    $localChecksums = getFileChecksums(true);
    $localChecksumsCount = count($localChecksums);
    sendLine('<font color="green">done</font> (' . $localChecksumsCount . ')<br>');
    // init some arrays
    $filesMissing = array();
    $filesNew = array();
    $filesOk = array();
    $filesChanged = array();
    // validate
    sendLine('<br><strong>Validating...</strong><br>');
    // validate pass 1
    foreach ($remoteChecksums as $file => $md5) {
        $line = tfb_htmlencodekeepspaces($file);
        if (isset($localChecksums[$file])) {
            if ($md5 == $localChecksums[$file]) {
                array_push($filesOk, $file);
                $line .= ' <font color="green"> Ok</font>';
            } else {
                array_push($filesChanged, $file);
                $line .= ' <font color="red"> Changed</font>';
            }
        } else {
            array_push($filesMissing, $file);
            $line .= ' <font color="red"> Missing</font>';
        }
        sendLine($line . "<br>");
    }
    // validate pass 2
    foreach ($localChecksums as $file => $md5) {
        if (!isset($remoteChecksums[$file])) {
            array_push($filesNew, $file);
        }
    }
    // summary
    sendLine('<h3>Done.</h3>');
    // files Total
    sendLine('<strong>' . _VERSION . ': </strong>' . $remoteChecksumsCount . '<br>');
    sendLine('<strong>Local: </strong>' . $localChecksumsCount . '<br>');
    // files Ok
    sendLine('<strong>Unchanged: </strong>' . count($filesOk) . '<br>');
    // files Missing
    sendLine('<strong>Missing: </strong>' . count($filesMissing) . '<br>');
    // files Changed
    sendLine('<strong>Changed: </strong>' . count($filesChanged) . '<br>');
    // files New
    sendLine('<strong>New: </strong>' . count($filesNew) . '<br>');
    if (count($filesNew) > 0) {
        sendLine('<br><strong>New Files: </strong><br>');
        foreach ($filesNew as $newFile) {
            sendLine(tfb_htmlencodekeepspaces($newFile) . '<br>');
        }
    }
}