<?php
/** Decoderen **/
function decode($sInput, $iKey) {
    $sInput = base64_decode($sInput);
    $iOffset = ($iKey + 112) / 12;
    $sOutput = '';
    for ($i = 4; $i < strlen($sInput); ++$i) {
        $sOutput .= chr(ord($sInput[$i]) - $iOffset);
    }
    return $sOutput;
}

/** Accounts van bugmenot ophalen **/
function getAccounts($sUrl) {
    /* Bugmenot pagina ophalen */
    if (($sContents = @file_get_contents('http://www.bugmenot.com/view/' . $sUrl)) === false) {
        return false;
    }

    /* Codesleutel opzoeken */
    preg_match('#var key = (-?\d+);#', $sContents, $aMatch);
    $iKey = $aMatch[1];

    /* Accounts filteren */
    preg_match_all('#<tr><th>Username </th><td><script>d\(\'([a-z0-9+=/]+)\'\);<\/script></td></tr>\s*<tr><th>Password </th><td><script>d\(\'([a-z0-9+=/]+)\'\);<\/script></td></tr>#si', $sContents, $aMatches, PREG_SET_ORDER);
    foreach ($aMatches as $aAccount) {
        /* Decoderen */
        $aAccounts[decode($aAccount[1], $iKey)] = decode($aAccount[2], $iKey);
    }
    return $aAccounts;
}

/** Voorkomen van accounts controleren **/
function getExists($sUrl, $sUser = null, $sPassword = null) {
    if (($aAccounts = getAccounts($sUrl)) === false) {
        /* Website is handmatig geblokkeerd of komt niet voor */
        return false;
    }
    if ($sUser === null) {
        /* Er zijn accounts bekend */
        return true;
    }
    if ($sPassword === null) {
        /* Bepaal of de username bekend is */
        return isset($aAccounts[$sUser]);
    }
    /* Bepaal of username en password combinatie bekend is */
    return isset($aAccounts[$sUser]) && $aAccounts[$sUser] === $sPassword;
    
}
?>
