HEX
Server: Apache/2.4.6 (CentOS) mpm-itk/2.4.7-04 mod_fcgid/2.3.9 PHP/5.4.16
System: Linux dvm.vladweb.ru 3.10.0-1160.119.1.el7.x86_64 #1 SMP Tue Jun 4 14:43:51 UTC 2024 x86_64
User: region-gk.ru (1016)
PHP: 8.2.27
Disabled: NONE
Upload Files
File: /home/bk/efi/eficenter.ru/core/class.Main.php
<?
/*
from BMVMX
*/
  class main
  {
    function main ()
    {
      global $CONFIG, $NEW, $OPEN_NEW, $TYPES, $lang, $Uploads, $UploadImgPath, $ImgPath, $Uploads,$AdminImgPath, $UploadImgPath;

      $path_to_scan = RP . $CONFIG['class_path'];
      $dirs = $this->getDirList ($path_to_scan);
      $count_of_dirs = count ($dirs);
      $CONFIG = array_merge ((array)$NEW, (array)$CONFIG);
      $CONFIG = array_merge ((array)$OPEN_NEW, $CONFIG);
      for ($i = 0; $i <= $count_of_dirs - 1; ++$i)
      {
        if (file_exists (RP . $CONFIG['class_path'] . $dirs[$i] . '/config.php'))
        {
          require_once RP . $CONFIG['class_path'] . $dirs[$i] . '/config.php';
          $CONFIG = array_merge ((array)$OPEN_NEW, $CONFIG);
          $CONFIG = array_merge ((array)$NEW, $CONFIG);
          $TYPES = array_merge ((array)$TYPES, (array)$TYPES_NEW);
          continue;
        }
        else
        {
          echo '���� �� ������� ������ �� ������!<br>';
          echo RP . $CONFIG['class_path'] . $dirs[$i] . '/config.php';
          continue;
        }
      }

      return TRUE;
    }

	function ixconv($str) { return iconv('utf-8', 'cp1251', $str); }

    function parsesitenameandport ($title)
    {
      $pos = NULL;
      if ('' != $title)
      {
        $title = str_replace ('http://', '', $title);
        $title = str_replace ('HTTP://', '', $title);
        $pos = strpos ($title, 'www.');
        if ((is_numeric ($pos) AND $pos < 1))
        {
          $title = substr_replace ($title, '', 0, 4);
        }

        $pos = strpos ($title, 'WWW.');
        if ((is_numeric ($pos) AND $pos < 1))
        {
          $title = substr_replace ($title, '', 0, 4);
        }

        $str = substr ($title, strlen ($title) - 1, 1);
        if ('/' == $str)
        {
          $title = substr_replace ($title, '', strlen ($title) - 1, 1);
        }

        $pos = strpos ($title, ':');
        if ($pos === FALSE)
        {
          $port = '';
        }
        else
        {
          $port = substr ($title, $pos);
          $title = substr ($title, 0, $pos);
        }

        return array ('name' => $title, 'port' => $port);
      }

      return FALSE;
    }

    function parsesitename ($title)
    {
      if (is_array ($arr = main::parseSiteNameAndPort ($title)))
      {
        return $arr['name'];
      }

      return FALSE;
    }

    function parsesiteport ($title)
    {
      if (is_array ($arr = main::parseSiteNameAndPort ($title)))
      {
        return $arr['port'];
      }

      return FALSE;
    }

    function getservername ()
    {
      global $db;
      $server = main::parseSiteName ($_SERVER['HTTP_HOST']);
      $domain_alias = '';
      $query = 'SELECT DISTINCT S.title, S.alias AS site_alias, A.alias';
      $query .= ' FROM sites_languages AS L, sites AS S LEFT JOIN sites_alias AS A ON S.id = site_id';
      $query .= ' WHERE category_id = S.id';
      $db->query ($query);
      while ($db->next_record ())
      {
        $alias = $db->f ('alias');
        $title = $db->f ('title');
        if ($server == $title)
        {
          return str_replace (array ('.', '-'), array ('_', '_'), $db->f ('site_alias')) . '_';
        }

        if ($server == $alias)
        {
          $domain_alias = $db->f ('site_alias');
          continue;
        }
      }

      return str_replace (array ('.', '-'), array ('_', '_'), ($domain_alias ? $domain_alias : $server)) . '_';
    }



    function getsiteconfig ()
    {
      global $db;
      $host = main::parseSiteName ($_SERVER['HTTP_HOST']);
      $ret = array ();
      $query = 'SELECT S.*, L.language, L.id  AS lang_id';
      $query .= ' FROM sites AS S INNER JOIN  sites_languages AS L';
      $query .= ' ON S.id = L.category_id WHERE S.title = \'' . $host . '\' AND L.is_default = \'1\'';
      $db->query ($query);
      if ($db->nf ())
      {
        $db->next_record ();
      }
      else
      {
        $query = 'SELECT S.*, L.language, L.id  AS lang_id';
        $query .= ' FROM sites_alias AS A, sites AS S INNER JOIN  sites_languages AS L';
        $query .= ' ON S.id = L.category_id WHERE A.alias = \'' . $host . '\' AND A.site_id=S.id AND L.is_default = \'1\'';
        $db->query ($query);
        if (!$db->nf ())
        {
          return FALSE;
        }

        $db->next_record ();
      }

      $ret['site_id'] = $db->f ('id');
      $ret['host'] = $db->f ('title');
      $ret['pref'] = str_replace (array ('.', '-'), array ('_', '_'), $db->f ('alias'));
      $ret['descr'] = $db->f ('descr');
      $ret['sitename'] = $db->f ('sitename');
      $ret['sitename_rus'] = $db->f ('sitename_rus');
      $ret['multilanguage'] = $db->f ('multilanguage');
      $ret['contact_email'] = $db->f ('contact_email');
      $ret['return_email'] = $db->f ('return_email');
      $ret['lang_id'] = $db->f ('lang_id');
      $ret['language'] = $db->f ('language');
      return $ret;
    }

    function geturlbyblock_id ($block_id)
    {
      global $db;
      global $server;
      global $lang;
      $block_id = (int)$block_id;
      if ($block_id)
      {
        $db->query ('SELECT a.site_id site_id, a.lang_id lang_id, b.title site, c.language lang
							FROM ' . $server . $lang . '_pages_blocks a,
								 sites b,
								 sites_languages c
							WHERE a.id = ' . $block_id . ' AND
								  a.site_id = b.id AND
								  a.lang_id = c.id');
        if (0 < $db->nf ())
        {
          $db->next_record ();
          $site_id = $db->f ('site_id');
          $lang_id = $db->f ('lang_id');
          $site = $db->f ('site');
          $lang = $db->f ('lang');
          $www = (0 === strpos ($_SERVER['HTTP_HOST'], 'www.') ? 'www.' : '');
          return '/admin.php?site_target=' . $www . $site . '&lang=' . $lang;
        }
      }

      return FALSE;
    }


    function getselecttag ($arr, $int)
    {
      $int = (int)$int;
      if (((is_array ($arr) AND $int < sizeof ($arr)) AND isset ($int)))
      {
        for ($i = 0; $i < sizeof ($arr); ++$i)
        {
          if ($i == $int)
          {
            $arr[$i]['option_select'] = 'selected';
            continue;
          }
          else
          {
            $arr[$i]['option_select'] = '';
            continue;
          }
        }

        return $arr;
      }

      return FALSE;
    }

    function getasocselecttag ($arr, $val)
    {
      if ((is_array ($arr) AND isset ($val)))
      {
        $i = 0;
        foreach ($arr as $k => $v)
        {
          if ($k == $val)
          {
            $prp[$i]['value'] = $k;
            $prp[$i]['descr'] = $v;
            $prp[$i]['option_select'] = 'selected';
          }
          else
          {
            $prp[$i]['value'] = $k;
            $prp[$i]['descr'] = $v;
            $prp[$i]['option_select'] = '';
          }

          ++$i;
        }

        return $prp;
      }

      return FALSE;
    }

    function searchinarrkeyanotherarr ($arr_1, $arr_2)
    {
      if ((is_array ($arr_1) AND is_array ($arr_2)))
      {
        foreach ($arr_2 as $k => $v)
        {
          if ((!array_key_exists ($k, $arr_1) OR $arr_1[$k] == ''))
          {
            $arr_1[$k] = $v;
            continue;
          }
        }

        return $arr_1;
      }

      return FALSE;
    }

    function makemergearray ($arr_1, $arr_2, $array_key = '')
    {
      global $CONFIG;
      if ($array_key != '')
      {
        $arr_1[$array_key] = main::searchInArrKeyAnotherArr ($arr_1[$array_key], $CONFIG[$array_key]);
      }

      if ((is_array ($arr_1) AND is_array ($arr_2)))
      {
        $max_k = 0;
        foreach ($arr_1 as $k => $v)
        {
          foreach ($v as $k_2 => $v_2)
          {
            if ($max_k < $k_2)
            {
              $max_k = $k_2;
              continue;
            }
          }

          $val_k = $k;
        }

        foreach ($arr_2 as $key => $val)
        {
          while ((array_key_exists ($key, $arr_1) OR $key <= $max_k))
          {
            ++$key;
          }

          $arr_1[$val_k][$key] = $val;
          $max_k = $key;
        }

        return $arr_1;
      }

      return $arr_1;
    }

    function makedefarraybyarray ($arr, $i = 0)
    {
      global $CONFIG;
      $tab = str_repeat ('	', $i);
      if (is_array ($arr))
      {
        ++$i;
        foreach ($arr as $key => $val)
        {
          $str .= $tab . '\'' . $key . '\' => ';
          if (is_array ($val))
          {
            $str_2 .= 'array(';
            $str_2 .= main::makeDefArrayByArray ($val, $i);
          }
          else
          {
            if ($val !== '')
            {
              $str .= '\'' . $val . '\',';
            }
            else
            {
              $str .= '\'\',';
            }
          }

          $str = $str . $tab . $str_2 . '
';
        }

        $ret = '
' . $str . $tab;
        if (1 < $i)
        {
          $ret .= '),';
        }

        return $ret;
      }

      return FALSE;
    }

    function getmoduleconf ($module = '', $file = 'config.php')
    {
      global $CONFIG;
      if ((isset ($module) AND $module != ''))
      {
        $filename = RP . $CONFIG['class_path'] . $module . '/' . $file;
      }
      else
      {
        $filename = RP . $file;
      }

      $f = fopen ($filename, 'r');
      $conf = fread ($f, filesize ($filename));
      fclose ($f);
      $start = strpos ($conf, '/* CONF:START */') + strlen ('/* CONF:START */');
      $end = strpos ($conf, '/* CONF:END */');
      $lenght = $end - $start;
      $conf = substr ($conf, $start, $lenght);
      return $conf;
    }

    function setmoduleconf ($arr = array (), $arr_2 = array (), $module = '', $file = 'config.php', $array_key = '')
    {
      global $CONFIG;
      if (is_array ($arr))
      {
        foreach ($arr as $k => $v)
        {
          $v = str_replace ('\\\'', '', $v);
          $v = str_replace ('\'', '', $v);
          $arr_3[$k] = $v;
        }

        $arr = $arr_3;
        if (is_array ($arr_2))
        {
          $arr = main::makeMergeArray ($arr, $arr_2, $array_key);
        }

        $str = main::makeDefArrayByArray ($arr) . '/* CONF:END */' . '
);
?>';
        if ($module)
        {
          $filename = RP . $CONFIG['class_path'] . $module . '/' . $file;
        }
        else
        {
          $filename = RP . $file;
        }

        @chmod ($filename, 511);
        $f = fopen ($filename, 'r+');
        $conf = fread ($f, filesize ($filename));
        $start = strpos ($conf, '/* CONF:START */') + strlen ('/* CONF:START */');
        ftruncate ($f, $start);
        fseek ($f, $start);
        fwrite ($f, $str);
        fclose ($f);
        @chmod ($filename, 493);
        return TRUE;
      }

      return FALSE;
    }

    function getintegerproperty ($k = NULL, $v = NULL, $types = NULL)
    {
      global $tpl;
      if (($types AND $types['access'] != 'private'))
      {
        $tpl->assign ('descr', $types['descr']);
        $tpl->assign ('name', $k);
        $tpl->newBlock ('block_integer');
        if ($v)
        {
          $tpl->assign ('value', $v);
        }
        else
        {
          $tpl->assign ('value', $types['defval']);
        }

        $tpl->assign ('name', $k);
        if ($types['access'] == 'readonly')
        {
          $tpl->assign ('readonly', 'readonly');
        }

        if ($types['access'] == 'disabled')
        {
          $tpl->assign ('readonly', 'disabled');
        }

        return TRUE;
      }

      return FALSE;
    }

    function getdoubleproperty ($k = NULL, $v = NULL, $types = NULL)
    {
      global $tpl;
      if (($types AND $types['access'] != 'private'))
      {
        $tpl->assign ('descr', $types['descr']);
        $tpl->assign ('name', $k);
        $tpl->newBlock ('block_double');
        if ($v)
        {
          $tpl->assign ('value', $v);
        }
        else
        {
          $tpl->assign ('value', $types['defval']);
        }

        $tpl->assign ('name', $k);
        if ($types['access'] == 'readonly')
        {
          $tpl->assign ('readonly', 'readonly');
        }

        if ($types['access'] == 'disabled')
        {
          $tpl->assign ('readonly', 'disabled');
        }

        return TRUE;
      }

      return FALSE;
    }

    function getstringproperty ($k = NULL, $v = NULL, $types = NULL)
    {
      global $tpl;
      if (($types AND $types['access'] != 'private'))
      {
        $tpl->assign ('descr', $types['descr']);
        $tpl->assign ('name', $k);
        $tpl->newBlock ('block_string');
        if ($v)
        {
          $tpl->assign ('value', $v);
        }
        else
        {
          $tpl->assign ('value', $types['defval']);
        }

        $tpl->assign ('name', $k);
        if ($types['access'] == 'readonly')
        {
          $tpl->assign ('readonly', 'readonly');
        }

        if ($types['access'] == 'disabled')
        {
          $tpl->assign ('readonly', 'disabled');
        }

        return TRUE;
      }

      return FALSE;
    }

    function getcheckboxproperty ($k = NULL, $v = NULL, $types = NULL)
    {
      global $tpl;
      if (($types AND $types['access'] != 'private'))
      {
        $v = ($v ? 'checked' : '');
        $tpl->assign ('descr', '' . $types['descr']);
        $tpl->assign ('name', $k);
        $tpl->newBlock ('block_checkbox');
        $tpl->assign ('value', $v);
        $tpl->assign ('name', $k);
        if ($types['access'] == 'disabled')
        {
          $tpl->assign ('readonly', 'disabled');
        }

        return TRUE;
      }

      return FALSE;
    }

    function getselectproperty ($k = NULL, $v = NULL, $types = NULL)
    {
      global $tpl;
      if (($types AND $types['access'] != 'private'))
      {
        $prp = $this->getAsocSelectTag ($types['defval'], $v);
        $tpl->assign ('descr', $types['descr']);
        $tpl->assign ('name', $k);
        $tpl->newBlock ('block_select');
        $tpl->assign ('name', $k);
        if ($types['access'] == 'disabled')
        {
          $tpl->assign ('readonly', 'disabled');
        }

        $tpl->assign_array ('block_select_row', $prp);
        return TRUE;
      }

      return FALSE;
    }

    function getpropertiesstrings ($NEW = NULL, $TYPES_NEW = NULL)
    {
      global $tpl;
      if ((is_array ($NEW) AND is_array ($TYPES_NEW)))
      {
        foreach ($NEW as $k => $v)
        {
          if ($TYPES_NEW[$k]['type'])
          {
            $tpl->newBlock ('block_property_row');
            switch ($TYPES_NEW[$k]['type'])
            {
              case 'integer':
              {
                $this->getIntegerProperty ($k, $v, $TYPES_NEW[$k]);
                break;
              }

              case 'double':
              {
                $this->getDoubleProperty ($k, $v, $TYPES_NEW[$k]);
                break;
              }

              case 'string':
              {
                $this->getStringProperty ($k, $v, $TYPES_NEW[$k]);
                break;
              }

              case 'checkbox':
              {
                $this->getCheckboxProperty ($k, $v, $TYPES_NEW[$k]);
                break;
              }

              case 'select':
              {
                $this->getSelectProperty ($k, $v, $TYPES_NEW[$k]);
              }
            }

            continue;
          }
        }
      }

      return FALSE;
    }

    function getmoduleproperties ($module = NULL)
    {
      global $tpl,$CONFIG;
      if ($module)
      {
        if (file_exists (RP . $CONFIG['class_path'] . $module . '/config.php'))
        {
          include RP . $CONFIG['class_path'] . $module . '/config.php';
          $this->getPropertiesStrings ($NEW, $TYPES_NEW);
        }

        return TRUE;
      }
      else
      {
        if (file_exists (RP . 'config.php'))
        {
          include RP . 'config.php';
          $this->getPropertiesStrings ($NEW, $TYPES_NEW);
        }

        return TRUE;
      }

      return FALSE;
    }

    function filterprp ($p = NULL, $types_new = NULL, $module = NULL)
    {
      if ((is_array ($p) AND is_array ($types_new)))
      {
        foreach ($types_new as $k => $v)
        {
          if (!array_key_exists ($k, $p))
          {
            $p[$k] = '';
            continue;
          }
        }

        foreach ($p as $k => $v)
        {
          if (array_key_exists ($k, $types_new))
          {
            $arr[$k] = $p[$k];
            continue;
          }
        }

        foreach ($types_new as $k => $v)
        {
          $arr_2[$k] = $arr[$k];
        }

        $arr = $arr_2;
        foreach ($arr as $k => $v)
        {
          switch ($types_new[$k]['type'])
          {
            case 'integer':
            {
              $vv = (int)$v;
              break;
            }

            case 'double':
            {
              $vv = (double)$v;
              break;
            }

            case 'select':
            {
              $z = '';
              foreach ($types_new[$k]['defval'] as $key => $val)
              {
                if ($key == $v)
                {
                  $y[0] = $v;
                  break;
                }

                $y[] = $key;
              }

              $vv = $y[0];
              break;
            }

            default:
            {
              $vv = $v;
              break;
            }
          }

          if ($module)
          {
            if (is_numeric (strpos ($k, $module)))
            {
              $prp[$k] = $vv;
              continue;
            }

            continue;
          }

          $prp[$k] = $vv;
        }

        return $prp;
      }

      return FALSE;
    }

    function setmoduleproperties ($module, $p, $types_new = NULL)
    {
       global $tpl,$CONFIG;
      if (is_array ($p))
      {
        if ($module)
        {
          include RP . $CONFIG['class_path']. $module . '/config.php';
          $prp = main::filterPrp ($p, $TYPES_NEW, $module);
          main::setModuleConf ($prp, NULL, $module);
        }
        else
        {
          if ($types_new)
          {
            $prp = main::filterPrp ($p, $types_new);
          }

          main::setModuleConf ($prp, NULL);
        }
      }

      return FALSE;
    }

    function getconftoform ($module = '', $file = '', $url = '')
    {
      $arr = main::getModuleConf ($module, $file);
      if (isset ($arr))
      {
        $arr = '$OPEN_NEW_CONF = array(' . $arr . ');';
        eval ($arr);
      }

      if ((is_array ($OPEN_NEW_CONF) AND 0 < sizeof ($OPEN_NEW_CONF)))
      {
        $i = 0;
        foreach ($OPEN_NEW_CONF as $key => $val)
        {
          if ((is_array ($val) AND 0 < sizeof ($val)))
          {
            foreach ($val as $key_2 => $val_2)
            {
              if ($val_2 !== '')
              {
                $form[$i]['conf_name'] = 'arr[' . $key . '][' . $key_2 . ']';
                $form[$i]['conf_val'] = $val_2;
              }

              ++$i;
            }

            continue;
          }
          else
          {
            if ($val !== '')
            {
              $form[$i]['conf_name'] = $key;
              $form[$i]['conf_val'] = $val;
              ++$i;
              continue;
            }

            continue;
          }
        }

        return $form;
      }

      return FALSE;
    }

    function getdirlist ($pth, $types = 'directories', $recursive = 0)
    {
      if ($dir = opendir ($pth))
      {
        $file_list = array ();
        while (false !== $file = readdir ($dir))
        {
          if (($file != '.' AND $file != '..'))
          {
            if ((is_dir ($pth . '/' . $file) AND ($types == 'directories' OR $types == 'all')))
            {
              $file_list[] = $file;
              if ($recursive)
              {
                $file_list = array_merge ($file_list, getdirlist ($pth . '/' . $file . '/', $types, $recursive));
                continue;
              }

              continue;
            }

            if (($types == 'files' OR $types == 'all'))
            {
              $file_list[] = $file;
              continue;
            }

            continue;
          }
        }

        closedir ($dir);
        return $file_list;
      }
      else
      {
        return FALSE;
      }

    }

    function files_list ($pth, $types = 'files', $recursive = 0)
    {
      if ($dir = @opendir ($pth))
      {
        $file_list = array ();
        while (FALSE !== $file = readdir ($dir))
        {
          if (($file != '.' AND $file != '..'))
          {
            if ((is_dir ($pth . '/' . $file) AND ($types == 'directories' OR $types == 'all')))
            {
              $file_list[] = $file;
              if ($recursive)
              {
                $file_list = array_merge ($file_list, $this->getDirList ($pth . '/' . $file . '/', $types, $recursive));
                continue;
              }

              continue;
            }

            if (($types == 'files' AND !is_dir ($pth . '/' . $file)))
            {
              $file_list[] = $file;
              continue;
            }
            else
            {
              if ($types == 'all')
              {
                $file_list[] = $file;
                continue;
              }

              continue;
            }

            continue;
          }
        }

        closedir ($dir);
        return $file_list;
      }

      return FALSE;
    }

    function show_list ($elm_arr, $blockname, $selected_elm = '')
    {
      global $CONFIG;
      global $tpl;
      foreach ($elm_arr as $elm_idx => $elm_val)
      {
        $selected = ($elm_idx == $selected_elm ? ' selected' : '');
        $tpl->newBlock ($blockname);
        $tpl->assign (array ('elm_idx' => $elm_idx, 'elm_val' => $elm_val, 'selected' => $selected));
      }

      return TRUE;
    }

    function get_rates ($show = '')
    {
      global $CONFIG;
      global $main;
      global $tpl;
      if (($CONFIG['catalog_upload_rates_file'] AND file_exists (RP . $CONFIG['catalog_upload_rates_file'])))
      {
        $lines = file (RP . $CONFIG['catalog_upload_rates_file']);
      }
      else
      {
        return FALSE;
      }

      foreach ($lines as $idx => $str)
      {
        $str = eregi_replace ('[[:space:]]', '', $str);
        if (eregi ('([[:alpha:]]+)/([[:alpha:]]+):([[:digit:].]+)', $str, $arr))
        {
          if ($show)
          {
            $tpl->assign ($arr[1] . '/' . $arr[2], $arr[3]);
            continue;
          }
          else
          {
            $_SESSION['catalog_rates'][$arr[1] . '/' . $arr[1]] = 1;
            $_SESSION['catalog_rates'][$arr[2] . '/' . $arr[2]] = 1;
            settype ($arr[3], 'double');
            $_SESSION['catalog_rates'][$arr[1] . '/' . $arr[2]] = $arr[3];
            $_SESSION['catalog_rates'][$arr[2] . '/' . $arr[1]] = 1 / $arr[3];
            continue;
          }

          continue;
        }
      }

      return TRUE;
    }

    function show_result_message ($result_message, $blockname = '')
    {
      global $CONFIG;
      global $main;
      global $tpl;
      if (!$blockname)
      {
        $blockname = 'block_result_message';
      }

      $main->include_main_blocks ('_result_message.html', 'main');
      $tpl->prepare ();
      $tpl->newBlock ($blockname);
      $tpl->assign ('result_message', $result_message);
      return TRUE;
    }

	function list_langs() {

		global $CONFIG, $core, $tpl, $name, $lang;

		$list_lang = '';

		if( $CONFIG['multilanguage'] == 'on' || $CONFIG['multilanguage'] == true ) {

			foreach($CONFIG['site_langs'] as $k => $lng) { //print $lng['value'] .'-'. $lang .'<br />';

				$list_lang .= ( ($lang === $lng['value']) ? '<li class="li_lang_active">'. $lng['value'] .' ('. $lng['name'] .')</li>'
				: '<li class="li_lang_no_active"><a href="admin.php?lang='. $lng['value'] .'" '. '>'. $lng['value'] .' ('. $lng['name'] .')</a></li>' );
			}

			return $list_lang;
		}
	}



    function show_admin_menu ($default_action = '')
    {
      global $CONFIG, $core, $tpl, $name, $lang,$gp_cmd;

      $site_link = $core->formPageLink ('', '', $lang);
      $lang_query = ($CONFIG['multilanguage'] ? 'lang=' . $lang . '&' : '');
      $path_to_scan = RP . $CONFIG['class_path'];

      $site_mods = main::getSiteModulesNames ();
      $menu = array ();

      $dirs = $this->getDirList ($path_to_scan);
      $count_of_dirs = count ($dirs);
      $menu_top = array ();

      $sub_menu = array ();
      $dirs = $this->getDirList ($path_to_scan);
      $count_of_dirs = count ($dirs);


      for ($i = 0; $i <= $count_of_dirs - 1; ++$i)
      {
        if (file_exists ($path_to_scan . $dirs[$i] . '/sub-menu.php'))
        {
          require_once $path_to_scan . $dirs[$i] . '/sub-menu.php';
          $sub_menu = array_merge ($sub_menu, (array)$sub_menu_new);
          continue;
        }
      }


      foreach ($site_mods as $key => $val)
      {
        $main_menu_item = $key;
        $main_menu_item_link = $val['link'];
        $main_menu_id = $val['id'];
      $module	=	$val;
if(!intval($key)) continue;
        if (isset($module) )
        {
          $img = ' class="curr"';
        }
        else
        {
          $img = '';
        }

        $tpl->assign (array ('main_menu_item' => $main_menu_item, 'main_menu_item_link' => $main_menu_item_link, 'img' => $img, 'main_menu_id' => $main_menu_id));






      if ((( is_array ($sub_menu[$module])) AND $name ==$val AND 0 < count ($sub_menu[$module])))
        {


      $action ='cmd=' . (
   	(	isset($_REQUEST['cmd']) && strlen($_REQUEST['cmd']))?$_REQUEST['cmd']:((	isset($gp_cmd) && strlen($gp_cmd))?$gp_cmd:((	isset($_REQUEST['action']) && strlen($_REQUEST['action']))?$_REQUEST['action']:$default_action)	)


   );

          $i = 0;
          $tpl->newBlock ('block_sub_menu');
          foreach ($sub_menu[$module] as $value)
          {
            ++$i;
            if ($i == 1)
            {
              $menu_item = $value;
            }

            if ($i == 2)
            {
              $menu_item_link = $value;
            }

            if ($i == 3)
            {

              $menu_item_icon = $value;

              $menu_item_class = ((strlen($action) AND (strpos ($menu_item_link,str_replace("cmd=","",$action)) )) ? 'class="current"' : '');
              $tpl->newBlock ('block_sub_menu_item');
              $tpl->assign (array ('menu_item' => $menu_item, 'menu_item_link' => $menu_item_link, 'menu_item_icon' => $menu_item_icon, 'menu_item_class' => $menu_item_class));
              $i = 0;
              continue;
            }
          }

          continue;
        }
      }

      return TRUE;
    }



    function getsitemodulesnames () {

	  global $db;
      $ret = array ();
      $query = 'SELECT M.name, M.title FROM sites AS S, modules AS M, sites_modules AS SM';
      $query .= ' WHERE  S.id = site_id AND M.id=module_id';
      $query .= ' AND !admin_only AND active';

      $db->query ($query);
      while ($db->next_record ())
      {
        $ret[] = $db->f ('name');
		$ret[$db->f ('name')] = $db->f ('title');
      }

      return $ret;
    }

    function get_modules_xml_format ($site_pref) {

	  global $db, $lang, $class_path, $CONFIG, $list_modules_xml; //pages
      $ret = array ();
      $query = 'SELECT M.name, M.title FROM sites AS S, modules AS M, sites_modules AS SM';
      $query .= ' WHERE alias=\'' . $site_pref . '\' AND S.id = site_id AND M.id=module_id';
      $query .= ' AND !admin_only AND active';

      $db->query ($query);
      while ($db->next_record ()) {

		//$ret[] = $db->f ('name');
		//$ret[$db->f ('name')] = $db->f ('title');

		if( $db->f ('name') != "pages" ) {

			$f = $CONFIG['class_path']. $db->f ('name'). '/tree_'. $db->f ('name') .'.php';
			if(file_exists($f)) {

				include_once( $f );
			}

		}

      }

      return $ret;
    }

    function tokenize ($string, $len = 30)
    {
      $string = strip_tags ($string);
      $tok = strtok ($string, '
	');
      $arr[] = $tok;
      while ($tok)
      {
        $tok = strtok ('');
        $arr[] = $tok;
      }

      $newarr = array_slice ($arr, 0, $len);
      $string = implode (' ', $newarr);
      $string = ($len + 1 < count ($arr) ? $string . '...' : $string);
      return $string;
    }

    function transform_date ($date, $hrs = '', $min = '')
    {
      list ($day, $month, $year) = preg_split ('|\\.|', $date);
      $time = (($hrs OR $min) ? '' . ' ' . $hrs . ':' . $min . ':00' : '');
      $date = '' . $year . '-' . $month . '-' . $day . $time;
      return $date;
    }

      function transform_date1 ($date)
    {
      list ($day, $month, $year) = preg_split ('|\\.|', $date);
       list ( $year,$time) = preg_split ('| |', $date);

      $date = '' . $year . '-' . $month . '-' . $day . $time;
      return $date;
    }



    function _show_nav_block ($pages, $blockname = null, $action = null, $current = null, $separator = null, $rewrite = false)
    {
      global $tpl, $name, $baseurl, $gp_total, $CONFIG, $lang, $admin_mode;

	  $rewrite = ( $admin_mode == true ) ? false : ( $CONFIG['rewrite_mod'] ? true : false );

	  $pages_in_block = $CONFIG['pages_in_block'];
      $nav_string = '';
      $url = $rewrite ? substr($baseurl, 0, strlen($baseurl) - 1) . $action : $baseurl . '&' . $action;

      $page_blocks = ceil ($pages / $pages_in_block);
      $current_block = ceil ($current / $pages_in_block);
      if (1 < $pages)
      {
        if (1 < $current)
        {
          $start_str = $rewrite ? '/p_'. ($current - 1) .'/' : '&p=' . ($current - 1);
          $nav_string = '' . '&nbsp;<a href="' . $url . $start_str . '">�������</a>&nbsp;' . $nav_string;
        }

        if (1 < $current_block)
        {
          $start_str = $rewrite ? '/p_' . (($current_block - 1) * $pages_in_block - ($pages_in_block - 1)) .'/'  : '&p=' . (($current_block - 1) * $pages_in_block - ($pages_in_block - 1));
          $nav_string = '' . '&nbsp;<a href="' . $url . $start_str . '">������</a>&nbsp;' . $nav_string;
        }

        $end = ($pages < $current_block * $pages_in_block ? $pages : $current_block * $pages_in_block);
        for ($i = ($current_block - 1) * $pages_in_block + 1; $i <= $end; ++$i)
        {
          $start_str = $rewrite ? ($i == 1 ? '' :  '/p_' . $i . '/') : ($i == 1 ? '' : '' . '&p=' . $i);
          $link = ($i == $current ? '' . '<span>' . $i . '</span>' : '' . '<a href="' . $url . $start_str . '">' . $i . '</a>');
          if ($i == $pages)
          {
            $separator = '&nbsp;';
          }

          $nav_string .= '' . $link . '&nbsp;';
        }

        if ($current < $pages)
        {
          $start_str = $rewrite ? '/p_' . ($current + 1) . '/' :  '&p=' . ($current + 1);
          $nav_string = $nav_string . ('' . '&nbsp;<a href="' . $url . $start_str . '">������</a>&nbsp;');
        }

        if ($current_block < $page_blocks)
        {
          $start_str = $rewrite ? '/p_' . ($current_block * $pages_in_block + 1) : '&p=' . ($current_block * $pages_in_block + 1);
          $nav_string = $nav_string . ('' . '&nbsp;<a href="' . $url . $start_str . '">�������</a>&nbsp;');
        }

        if (!$blockname)
        {
          $blockname = 'nav';
        }

        $tpl->newBlock ($blockname);
        $tpl->assign (array ('nav_string' => $nav_string));
      }

      return $nav_string;
    }

    function _show_nav_string ($table = null, $where = null, $blockname = null, $action = null, $current = null, $rows = 10, $order_by = null, $separator = null, $admin = 1, $only_active = 1, $rewrite = false)
    {

      global $tpl, $name, $baseurl, $gp_total, $CONFIG, $lang;
$nav_string	=	'';
      $current = (int)$current;
       $rewrite	=	true;
      if ($current <= 0)
      {
        $current = 1;
      }

      if ($order_by)
      {
        $order_by = '' . 'ORDER BY ' . $order_by;
      }

      $total = 0;
      if ((!$admin AND $only_active))
      {
        $where .= ' AND active = 1';
      }

      $query = '' . 'SELECT COUNT(*) as count FROM ' . $table . ' WHERE 1=1 ' . $where . ' ' . $order_by;
      $res = db_loadresult ($query);
      if ($res)
      {
        $total = $res;
      }

      if ($total)
      {
        $GLOBALS['nav_total'] = $total;
        $GLOBALS['request_total'] = $total;
        if($rows==0)$rows=1;
        $pages = ceil ($total / $rows);
        $nav_string = $this->_show_nav_block ($pages, $blockname, $action, $current, $separator, $rewrite);
      }

      return $nav_string;
    }

    function _show_nav_string_2 ($col = null, $table = null, $where = null, $blockname = null, $action = null, $current = null, $rows = 10, $order_by = null, $separator = null, $admin = 1, $only_active = 1)
    {
     $rewrite	=	true;
      global $tpl;
      global $name;
      global $baseurl;
      global $gp_total;
      global $CONFIG;
      global $lang;
      $current = (int)$current;
      if ($current <= 0)
      {
        $current = 1;
      }

      if ($order_by)
      {
        $order_by = '' . 'ORDER BY ' . $order_by;
      }

      $total = 0;
      if ((!$admin AND $only_active))
      {
        $where .= ' AND active = 1';
      }

      if ($col)
      {
        $query = '' . 'SELECT COUNT(DISTINCT ' . $col . ') as count FROM ' . $table . ' WHERE 1=1 ' . $where . ' ' . $order_by;
      }
      else
      {
        $query = '' . 'SELECT COUNT(*) as count FROM ' . $table . ' WHERE 1=1 ' . $where . ' ' . $order_by;
      }

      $res = db_loadresult ($query);
      if ($res)
      {
        $total = $res;
      }

      if ($total)
      {
        $GLOBALS['nav_total'] = $total;
        $GLOBALS['request_total'] = $total;
        if($rows==0)$rows=1;
        $pages = ceil ($total / $rows);
        $nav_string = $this->_show_nav_block ($pages, $blockname, $action, $current, $separator);
      }

      return $nav_string;
    }

    function include_main_blocks ($template = '_empty.html', $mode = '')
    {
      global $tpl_path;
      global $tpl;
      global $name;
      global $server;
      global $lang;

      if ($mode == 'main')
      {
        $tpl = new TemplatePower ($tpl_path . $template);
      }
      else
      {
        $tpl->assignInclude ('menu', $tpl_path . '_menu.html');
        $tpl->assignInclude ('sub_menu', $tpl_path . '_sub_menu.html');
        $tpl->assignInclude ('main', $tpl_path . $template);
      }

      return TRUE;
    }

    function include_main_blocks_2 ($template = '_empty.html', $tpl_path_2, $mode = '')
    {
      global $tpl_path;
      global $tpl;
      global $name;
      global $lang;
      if ($mode == 'main')
      {
        $tpl = new TemplatePower ($tpl_path_2 . $template);
      }
      else
      {
        $tpl->assignInclude ('menu', $tpl_path . '_menu.html');
        $tpl->assignInclude ('sub_menu', $tpl_path . '_sub_menu.html');
        $tpl->assignInclude ('main', $tpl_path_2 . $template);
      }

      return TRUE;
    }

    function show_actions ($field = '', $default_action = '', $block_main_module_actions = array (), $block_module_actions = array ())
    {
      global $tpl;
      global $mod;
      global $lang;
      if ((($field == 0 AND is_array ($block_main_module_actions)) AND 0 < count ($block_main_module_actions)))
      {
        $action_array = $block_main_module_actions;
      }
      else
      {
        $action_array = $block_module_actions;
      }

      if ((is_array ($action_array) AND 0 < count ($action_array)))
      {
        $tpl->newBlock ('block_select_actions');
        foreach ($action_array as $act => $descr)
        {
          $tpl->newBlock ('block_available_actions');
          $selected = ($act == $default_action ? ' selected' : '');
          $tpl->assign (array ('action' => $act, 'description' => $descr, 'selected' => $selected));
        }

        $tpl->newBlock ('block_properties');
      }
      else
      {
        $tpl->assign ('no_action', '�� ������� ����� ������� �� ���������');
        return FALSE;
      }

      return TRUE;
    }

    function show_linked_pages ($module_id, $field = null)
    {
      global $name, $lang;

	  $tree_elem_add = '';

      if ($res = $this->get_linked_pages ($module_id)) {

        foreach ($res as $r) {
          //$tpl->assign (array (page_title => $r['title'], page_link => $r['link'], page_id => $r['page_id']));
		  $tree_elem_add .= '<linkedpages value="'. str_replace(array("<", ">", "\""), "", $r['link']) .'">'. htmlspecialchars($r['title']) .'</linkedpages>';
        }

        return $tree_elem_add;
      }
    }

    function get_linked_pages ($module_id)
    {
      global $lang;
 $module_id = (int) $module_id;
      if (!$module_id) return false;

      $res = db_loadlist ('SELECT ' . $lang . '_pages.title as title,
								   ' . $lang . '_pages.link as link,
								   ' . $lang . '_pages.address as address,
								   ' . $lang . '_pages_blocks.*
							   FROM ' . $lang . '_pages_blocks,
							   		' . $lang . '_pages
							   WHERE module_id = ' . $module_id . ' AND
							   		 field_number = 0 AND
							   		 ' . $lang . '_pages.id = page_id
							   GROUP BY ' . $lang . '_pages.id
							   ORDER BY page_id');

      return $res;
    }

    function permanent_address ()
    {
      return '�������� �����: <a href="' . $_SERVER['REQUEST_URI'] . '">http://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'] . '</a>';
    }

    function suspend ($table, $id, $field = 'active',$fid = 'id')
    {
      $id = (int)$id;
      if (!$id)
      {
        return FALSE;
      }

      $query = 'UPDATE ' . $table . ' SET ' . $field . ' = 0 WHERE  '.$fid.' = ' . $id;

      db_exec ($query);
      return TRUE;
    }

    function activate ($table, $id, $field = 'active',$fid = 'id')
    {
      global $lang;
      $id = (int)$id;
      if (!$id)
      {
        return FALSE;
      }

      $query = 'UPDATE ' . $table . ' SET ' . $field . ' = 1 WHERE '.$fid.' = ' . $id;
      db_exec ($query);
      return TRUE;
    }



    function testfiles ($file)
    {
      if (eregi ('' . '\\.(phtml|php|php3|php4|php5|shtml|cgi|exe|pl|asp|aspx|htaccess|htgroup|htpasswd)$', $file))
      {
        $this->_die ('<span class="title">����������� ������ ����� ' . $file . '!</span>');
        return FALSE;
      }

      return TRUE;
    }

    function uploadfiles ($formname, $max_size, $path, $dir = null, $file_formats = array (), $lid = '')
    {
      global $lang;
      global $db;
      foreach ($_FILES[$formname]['name'] as $key => $v)
      {
        foreach ($v as $k => $val)
        {
          foreach ($val as $k2 => $v2)
          {
            if (!$this->testFiles ($val[$k2]))
            {
              return FALSE;
              continue;
            }
          }
        }
      }

      foreach ($_FILES[$formname]['name'] as $key => $v)
      {
        foreach ($v as $k => $val)
        {
          if ((isset ($key) AND !@is_numeric ($key)))
          {
            if ((isset ($val) AND $val != ''))
            {
              $new_name = $lid . '_other_' . $val;
              unlink ($path . $key);
              if (move_uploaded_file ($_FILES[$formname]['tmp_name'][$key][$k], $path . $new_name))
              {
                @chmod ($path . $new_name, 495);
                $fls_chg[$key] = $new_name;
                continue;
              }

              continue;
            }

            continue;
          }

          if ((isset ($key) AND @is_numeric ($key)))
          {
            foreach ($val as $k2 => $v2)
            {
              $new_name = $lid . '_' . $key . '_' . $k2 . '_' . $val[$k2];
              if (move_uploaded_file ($_FILES[$formname]['tmp_name'][$key][$k][$k2], $path . $new_name))
              {
                @chmod ($path . $new_name, 495);
                $fls_chg[] = $new_name;
                continue;
              }
            }

            continue;
          }
        }
      }

      if ($fls_chg)
      {
        return $fls_chg;
      }

      return TRUE;
    }

    function upload_file ($formname, $max_size, $path, $dir = null, $file_formats = array (), $set_file_name = '')
    {
      if (is_array ($_FILES[$formname]['name']))
      {
        return $this->uploadFiles ($formname, $max_size, $path, $dir, $file_formats, $set_file_name);
      }

      if (preg_match ('#' . '\\.(phtml|php|php3|php4|php5|shtml|cgi|exe|pl|asp|aspx|htaccess|htgroup|htpasswd|inc)$#i', $_FILES[$formname]['name']))
      {
        $this->_die ('<span class="title">����������� ������ ����� ' . $_FILES[$formname]['name'] . '!</span>');
        return false;
      }

      if (!$_FILES[$formname]['name'])
      {
        $this->_die ('<span class="title">����� ������ ����� ' . $_FILES[$formname]['name'] . '!</span>');
        return false;
      }

      $new_name = $_FILES[$formname]['name'];
      if ($set_file_name)
      {
        $new_name = $set_file_name;
      }

      if (0 < count ($file_formats))
      {
        foreach ($file_formats as $key => $val)
        {
          if ($_FILES[$formname]['type'] == $key)
          {
            $format = $val;
            break;
          }
        }

        if (!$format)
        {
          $this->_die ('<span class="title">����������� ������ ����� ' . $_FILES[$formname]['type'] . '!</span>');
          return false;
        }
      }

      if ($max_size)
      {
        if ($max_size < $_FILES[$formname]['size'])
        {
          $this->_die ('<span class="title">������ ����� ������ �����!</span>');
          return false;
        }
      }

      if ($dir)
      {
        $path = $path . $dir . '/';
      }

      if (!is_dir ($path))
      {
        $this->_die ('' . '<span class="title">���������� ��� ������ ' . $path . '!</span>');
        return false;
      }

      if ((file_exists ($path . $new_name) AND !$set_file_name))
      {
        $pos = strrpos ($new_name, '.');
        if ($pos)
        {
          if (!$format)
          {
            $format = substr ($new_name, $pos + 1, strlen ($new_name));
          }

          $new_name = substr ($new_name, 0, $pos) . '-' . mt_rand (100, 999) . '.' . $format;
        }
      }

      if (move_uploaded_file ($_FILES[$formname]['tmp_name'], $path . $new_name))
      {
        @chmod ($path . $new_name, 495);
        return $new_name;
      }

      $this->_die ('<span class="title">����� ������ ����� ' . $path . $new_name . '!</span>');
      return false;
    }

    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    function change_order_nw ($operation, $table, $field, $current_rank, $shift, $where_additional = null,$fid = 'id')
    {

      global $module_id;
      global $lang;
      $shift = (int)$shift + 1;
      $current_rank = (int)$current_rank;
 
     $query = '' . 'SELECT * FROM ' . $table . ' WHERE ' . $where_additional . ' 1 ORDER BY ' . $field . ' ASC';
      
    
//echo ($query);
      $res = db_loadlist ($query);
      if (1 < count ($res))
      {
        $i = 1;
        $ids = array ();
        $orders = array ();
        
        
        
 foreach ($res as $r)
        {
        
        

        
        
      
          
          
     //   var_dump($current_rank);     
        if($r[$fid]==$current_rank){
   
         if ($operation == 'up')
      {
      
      
      $it =$ids[($i-1)]; //$r[$fid];
      
        $ids[($i-1)] = $r[$fid];
        
          
        $ids[$i] = $it;
       
          
//           var_dump(current($ids));
//            var_dump($current_rank);
//              var_dump($it);
//                var_dump($ot);
//           
          
          
      }else{
      
      $tmp = current($res);

      $current_rank = $tmp[$fid];
      
     // var_dump($current_rank);
      $operation = 'up';

  
     $ids[$i] = $r[$fid];
      
    //  $tmp = prev($res);
        //  $orders[] = $i;
 }
        
        }else{
        
           $ids[$i] = $r[$fid];
 
        }
     
    

          ++$i;
        }

     //   array_unshift ($orders, array_pop ($orders));
   //   var_dump($ids);
     //   die($ids);
        foreach ($ids as $idx => $id)
        {

            $query = '' . 'UPDATE ' . $table . ' SET ' . $field . ' = ' . $idx . ('' . ' where '.$fid.' = ' . $id);
	//  echo ($query);
            db_exec ($query);
            continue;
      
        }

        return TRUE;
      }

      return FALSE;
    }

    
    
    function change_order ($operation, $table, $field, $current_rank, $shift, $where_additional = null,$fid = 'id')
    {

      global $module_id;
      global $lang;
      $shift = (int)$shift + 1;
      $current_rank = (int)$current_rank;
      if ($operation == 'down')
      {
        $query = '' . 'SELECT * FROM ' . $table . ' WHERE ' . $where_additional . ' ' . $field . ' >= ' . $current_rank . ' ORDER BY ' . $field . ' ASC LIMIT 0,' . $shift;
      }
      else
      {
        $query = '' . 'SELECT * FROM ' . $table . ' WHERE ' . $where_additional . ' ' . $field . ' <= ' . $current_rank . ' ORDER BY ' . $field . ' DESC LIMIT 0,' . $shift;
      }

      $res = db_loadlist ($query);
      if (1 < count ($res))
      {
        $i = 1;
        $ids = array ();
        $orders = array ();
        foreach ($res as $r)
        {
          $ids[] = $r[$fid];
          $orders[] = $r[$field];
          if ($i == $shift)
          {
            break;
          }

          ++$i;
        }

        array_unshift ($orders, array_pop ($orders));
        foreach ($ids as $idx => $id)
        {
          if ($orders[$idx])
          {
            $query = '' . 'UPDATE ' . $table . ' SET ' . $field . ' = ' . $orders[$idx] . ('' . ' where '.$fid.' = ' . $id);
	  //  die($query);
            db_exec ($query);
            continue;
          }
        }

        return TRUE;
      }

      return FALSE;
    }

    function get_max_min_rank ($table, $field = 'rank', $where = '')
    {
      global $lang;
      $query = '' . 'SELECT MAX(' . $field . ') as max_rank, MIN(' . $field . ') as min_rank FROM ' . $table . ' ' . $where;
      $res = db_loadresult2 ($query);
      if ($res)
      {
        $max_rank = $res['max_rank'];
        $min_rank = $res['min_rank'];
      }

      if (!$max_rank)
      {
        $max_rank = 1;
      }

      if (!$min_rank)
      {
        $min_rank = -1;
      }

      return array ($max_rank, $min_rank);
    }

    function _die ($msg_text)
    {
      exit ($msg_text . '
      <a href="javascript:history.go(-1);"> &laquo;&laquo; ����� </a>');
    }

    function message_access_denied ($name, $action)
    {

      $this->_die ('

		<br /><span style="color: red;">� ��� ��� ������� �� ���� �������! ��������� � ��������������!</span><br />

		');
    }

    function no_such_page ()
    {
      global $main;
      global $CONFIG;
      global $server;
      global $lang;

      global $tpl;
      header ('HTTP/1.0 404 Not Found');
      $address = $CONFIG['web_address'] . $_SERVER['REQUEST_URI'];
      $address = str_replace ('http://', 'http:::', $address);
      $address = str_replace ('//', '/', $address);
      $address = str_replace ('http:::', 'http://', $address);
      $address = preg_replace ('/[(\\;)(\\|)(\\\')(")(\\!)(\\<)(\\>)]/', '', $address);

      $map_link = core::formPageLink ($CONFIG['map_page_link'], $CONFIG['map_page_address'], $lang);
      $home_link = core::formPageLink ('', '', $lang);
      $main->include_main_blocks_2 ('404.html', $CONFIG['tpl_path'] . $lang . '/', 'main');
      $tpl->prepare ();
      $tpl->assign (array ('_ROOT.address' => $address, '_ROOT.map_link' => $map_link, '_ROOT.home_link' => $home_link, '_ROOT.contact_email' => $CONFIG['contact_email']));
      $tpl->printToScreen ();
      $content = ob_get_contents ();
      ob_end_clean ();
      if (((($_SERVER['HTTP_ACCEPT_ENCODING'] AND FALSE !== strpos ($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip')) AND 0 < $CONFIG['front_office_zip']) AND $CONFIG['front_office_zip'] <= 9))
      {
        $content = gzencode ($content, $zip);
        header ('Content-Encoding: gzip');
      }

      header ('Content-Length: ' . strlen ($content));
      echo $content;
      exit ();
    }


	function head_xml() {

		header("Content-type: text/xml");
		header("Cache-Control: no-store, no-cache, must-revalidate");
		header("Cache-Control: post-check=0, pre-check=0", false);
	}

	function head_cp1251() {

		header("Content-type: text/plain; charset=windows-1251");
		header("Cache-Control: no-store, no-cache, must-revalidate");
		header("Cache-Control: post-check=0, pre-check=0", false);
	}

    function login_form_page ()
    {
      global $main;
      global $CONFIG;
      global $server;
      global $lang;

      global $tpl;
      global $gp_mode;
      $address = $CONFIG['web_address'] . $_SERVER['REQUEST_URI'];
      $address = str_replace ('http://', 'http:::', $address);
      $address = str_replace ('//', '/', $address);
      $address = str_replace ('http:::', 'http://', $address);
      $address = preg_replace ('/[(\\;)(\\|)(\\\')(")(\\!)(\\<)(\\>)]/', '', $address);

      $map_link = core::formPageLink ($CONFIG['map_page_link'], $CONFIG['map_page_address'], $lang);
      $home_link = core::formPageLink ('', '', $lang);
      $main->include_main_blocks_2 ('login.html', 'tpl/' . $server . $lang . '/', 'main');
      $tpl->prepare ();
      $tpl->assign (array ('_ROOT.address' => $address, '_ROOT.map_link' => $map_link, '_ROOT.home_link' => $home_link, '_ROOT.contact_email' => $CONFIG['contact_email']));
      if ($gp_mode == 'remind')
      {
        $tpl->newBlock ('block_remind_form');
        $tpl->newBlock ('block_remind_text');
      }
      else
      {
        $tpl->newBlock ('block_authorize_form');
        $tpl->newBlock ('block_remind_link');
      }

      if ($gp_mode == 'logged_in')
      {
        $tpl->newBlock ('block_logged_in');
      }
      else
      {
        if ($gp_mode == 'logged_out')
        {
          $tpl->newBlock ('block_logged_out');
        }
        else
        {
          if ($gp_mode == 'access_denied')
          {
            $tpl->newBlock ('block_access_denied');
          }
          else
          {
            if ($gp_mode == 'incorrect')
            {
              $tpl->newBlock ('block_incorrect');
            }
            else
            {
              if ($gp_mode == 'reminded')
              {
                $tpl->newBlock ('block_reminded');
              }
              else
              {
                if ($gp_mode == 'mail_error')
                {
                  $tpl->newBlock ('block_mail_error');
                }
                else
                {
                  if ($gp_mode == 'not_found')
                  {
                    $tpl->newBlock ('block_not_found');
                  }
                  else
                  {
                    if (!$gp_mode)
                    {
                      $tpl->newBlock ('block_default');
                    }
                  }
                }
              }
            }
          }
        }
      }

      $tpl->printToScreen ();
      $content = ob_get_contents ();
      ob_end_clean ();
      if (((($_SERVER['HTTP_ACCEPT_ENCODING'] AND FALSE !== strpos ($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip')) AND 0 < $CONFIG['front_office_zip']) AND $CONFIG['front_office_zip'] <= 9))
      {
        $content = gzencode ($content, $zip);
        header ('Content-Encoding: gzip');
      }

      header ('Content-Length: ' . strlen ($content));
      echo $content;
      exit ();
    }

    function getmicrotime ()
    {
      list ($usec, $sec) = explode (' ', microtime ());
      return (double)$usec + (double)$sec;
    }

    function file_get_contents ($filename, $use_include_path = 0)
    {
      $data = '';
      $file = @fopen ($filename, 'r', $use_include_path);
      if ($file)
      {
        while (!feof ($file))
        {
          $data .= fread ($file, 1024);
        }

        fclose ($file);
      }

      return $data;
    }

    function generate_image ($source, $destination, $w, $h, $action_type = '', $filetype = '', $string = '', $jpeg_quality = '90')
    {
      global $CONFIG;
      $size = getimagesize ($source);
      if (!$filetype)
      {
        $filetype = $size['mime'];
      }

      if ((($filetype == 'image/jpeg' OR $filetype == 'image/pjpeg') OR $filetype == 'image/jpg'))
      {

        $src = imagecreatefromjpeg($source);



      }
      else
      {
        if ($filetype == 'image/gif')
        {
          $src = imagecreatefromgif ($source);
        }
        else
        {
          if ($filetype == 'image/x-png')
          {
            $src = imagecreatefrompng ($source);
          }
          else
          {
            return 0;
          }
        }
      }

      ($dest = imagecreatetruecolor($w, $h) OR $this->_die ('Cannot Initialize new GD image stream'));

      if (($src AND $dest))
      {
        $sh = $size[1];
        $sw = $size[0];
        if ($action_type == 'resize')
        {
          imagecopyresampled($dest, $src, 0, 0, 0, 0, $w, $h, $sw, $sh);
        }
        elseif($action_type == 'resizew')
        	{
         $dh = (int)$sh * ($w / $sw);
          @imagedestroy ($dest);
         $dest = imagecreate ($w, $dh)  ;
            imagecopyresampled($dest, $src, 0, 0, 0, 0, $w, $dh, $sw, $sh);
        	}
        else
        {
          if ($action_type == 'square')
          {
            if ($sh < $sw)
            {
              ($tmp = imagecreate ($sw, $sh) OR $this->_die ('Cannot Initialize new GD image stream'));
              imagecopyresampled($dest, $src, 0, 0, 0, 0, $w, $h, $sw, $sh);
           }
            else
            {
              if ($sw < $sh)
              {
                 ($tmp = imagecreate ($sw, $sh) OR $this->_die ('Cannot Initialize new GD image stream'));
                imagecopyresampled($dest, $src, 0, 0, 0, 0, $w, $h, $sw, $sh);
               }
              else
              {
                imagecopyresampled($dest, $src, 0, 0, 0, 0, $w, $h, $sw, $sh);
              }
            }

            @imagedestroy($tmp);
          }
          else
          {
            imagecopyresampled($dest, $src, 0, 0, 0, 0, $w, $h, $w, $h);
          }
        }

        if ($string)
        {
          $bg = imagecolorallocatealpha ($dest, 0, 0, 0, 200);
          $text_color = imagecolorallocate ($dest, 255, 255, 255);
          imagefilledrectangle ($dest, 0, 0, 6 + strlen ($string) * 8, 23, $bg);
          imagestring ($dest, 3, 5, 5, $string, $text_color);
        }

        if ((($filetype == 'image/jpeg' OR $filetype == 'image/pjpeg') OR $filetype == 'image/jpg'))
        {
          imagejpeg ($dest, $destination, $jpeg_quality);
        }
        else
        {
          if ($filetype == 'image/gif')
          {
            imagegif ($dest, $destination);
          }
          else
          {
            if ($filetype == 'image/x-png')
            {
              imagepng ($dest, $destination);
            }
          }
        }

        @imagedestroy ($src);
        @imagedestroy ($dest);
        return TRUE;
      }

      return FALSE;
    }
    //����� ������� ���������� JPEG
  function resize_by_width_height ($imagename, $path, $image_size_w = 100,$image_size_h = 100, $type = '', $string = NULL, $jpeg_quality = 85, $action	=	'c')
   {
  // $string	=	"DRK" ;
   /// ������� ����������� (����� ���)
$src_fname = $path.$imagename ;
  /// ������� ������ ������� (����� ���)
$dst_fname = $path.$imagename;


$i_attr	=	@getimagesize($src_fname);
 if($i_attr == NULL)return FALSE;
	$width		= $i_attr[0];
	$height		= $i_attr[1];
	$type		= $i_attr[2];

///  ������� ��� ����������
	$im_ext	= '';
	if($i_attr[2]==2) {
		$im_src	= imagecreatefromjpeg($src_fname);
		$im_ext	= '.jpg';
	}


if($width<$height){
$image_size_w_tmp = $image_size_w	;
$image_size_h_tmp = $image_size_h;
$image_size_h = $image_size_w_tmp;
$image_size_w = $image_size_h_tmp;
}
	if(!$im_src)
		return false;
  $xs	=	$ys	=	$xd	=	$yd	=	0;

switch($action)
{

case 'c':

if($width > $image_size_w || $height > $image_size_h) {

/*@
/*@NEW VERSION@
/*@@
*/
 	$img_width	= ($height/$image_size_h <= $width/$image_size_w)?round ($width * ($image_size_h / $height)):$image_size_w;
	$img_height	 =($height/$image_size_h <= $width/$image_size_w)?$image_size_h:round ($height * ($image_size_w / $width));


	} else {

	//���� ����� ����������� ������� ������
           $image_size_w	=	$img_width = $width;
           $image_size_h	= $img_height =	 $height;
	}



$xd	= ($img_width<$image_size_w)?(int)round (($image_size_w-$img_width)/2):0;
$yd 	= ($img_height<$image_size_h)?(int)round (($image_size_h-$img_height)/2):0;
$xs	= ($img_width>=$image_size_w)?(int)round (($img_width-$image_size_w)/2):0;
$ys 	= ($img_height>=$image_size_h)?(int)round (($img_height-$image_size_h)/2):0;

break;
case 'wh':
if($width > $image_size_w || $height > $image_size_h) {

		if($width < $height) {
		$img_height	= $image_size_h;
			$img_width = round ($width * ($image_size_h / $height));


		}
		 else {

			$img_width	= $image_size_w;
			$img_height = round ($height * ($image_size_w / $width));
				}
	} else {

	//���� ����� ����������� ������� ������
          	$img_width =   $width;
            $img_height =  $height;


	}



$xd	= ($img_width<$image_size_w)?(int)round (($image_size_w-$img_width)/2):0;
$yd 	= ($img_height<$image_size_h)?(int)round (($image_size_h-$img_height)/2):0;

 break;
default:
	$img_width =   $image_size_w;
	$img_height =  $image_size_h;
break;


}
	$im_s 	= imagecreatetruecolor($img_width, $img_height);
	$im_full= imagecreatetruecolor($image_size_w, $image_size_h);
			  imagecopyresampled($im_s, $im_src, 0, 0, 0, 0, $img_width, $img_height, $width, $height);
         $bg = imagecolorallocate($im_full, 255, 255, 255);
	       	imagefilledrectangle ($im_full, 0, 0, $image_size_w, $image_size_h, $bg);
	 		imagecopy($im_full, $im_s, $xd, $yd, $xs, $ys, $img_width, $img_height);

	  if (strlen($string))
        {
       // var_dump(strlen($string));
      //  var_dump($string);
          $text_color = imagecolorallocate ($im_full, 127, 127, 127);
          imagestring ($im_full, 2, ($image_size_w -(6 + strlen ($string) * 8)), ($image_size_h-12), $string, $text_color);
        }

	imagejpeg($im_full, $dst_fname, $jpeg_quality);
	imagedestroy($im_full);
	imagedestroy($im_src);
	imagedestroy($im_s);
	@chmod($dst_fname, 0664);
	return true;


    }










    function resize_by_width ($imagename, $path, $max_width, $filetype = '', $string = NULL, $jpeg_quality = 100)
    {
      global $CONFIG;
      if (file_exists ($path . $imagename))
      {
        list ($w, $h) = getimagesize ($path . $imagename);
        if ($max_width < $w||$max_width==100)
        {
          $dh = (int)$h * ($max_width / $w);
          if ($this->generate_image ($path . $imagename, $path . $imagename, $max_width, $dh, 'resize', $filetype, $string, $jpeg_quality))
          {
            return TRUE;
          }
        }
      }

      return TRUE;
    }


 function  translit($str) {

$str = trim($str);

  $ttable = array(
	  "\\" => "",
	  "%" => "",
	  "/" => "",
	  "*" => "",
	  ":" => "",
	  "?" => "",
	  "\"" => "",
	  ">" => "",
	  "<" => "",
	  "|" => "",
	  ")'" => "",
	  "(" => "",
	  "!" => "",
	  "�" => "ij",
      "�" => "ts",
      "�" => "u",
      "�" => "k",
      "�" => "e",
      "�" => "n",
      "�" => "g",
      "�" => "sh",
      "�" => "shh",
      "�" => "z",
      "�" => "h",
      "�" => "`",
      "�" => "f",
      "�" => "y",
      "�" => "v",
      "�" => "a",
      "�" => "p",
      "�" => "r",
      "�" => "o",
      "�" => "l",
      "�" => "d",
      "�" => "zh",
      "�" => "je",
      "�" => "ia",
      "�" => "ch",
      "�" => "s",
      "�" => "m",
      "�" => "i",
      "�" => "t",
      "�" => "",
      "�" => "b",
      "�" => "ju",
      "�" => "jo",
      " " => "_",
      "�" => "IJ",
      "�" => "TS",
      "�" => "U",
      "�" => "K",
      "�" => "E",
      "�" => "N",
      "�" => "G",
      "�" => "SH",
      "�" => "SHH",
      "�" => "Z",
      "�" => "H",
      "�" => "`",
      "�" => "F",
      "�" => "Y",
      "�" => "V",
      "�" => "A",
      "�" => "P",
      "�" => "R",
      "�" => "O",
      "�" => "L",
      "�" => "D",
      "�" => "ZH",
      "�" => "JE",
      "�" => "IA",
      "�" => "CH",
      "�" => "S",
      "�" => "M",
      "�" => "I",
      "�" => "T",
      "�" => "",
      "�" => "B",
      "�" => "JU",
      "�" => "JO",
   );

     $result = strtr($str, $ttable);
    return $result;
}


function mailto($params)
{
    $extra = '';

    if (empty($params['address'])) {
        die("mailto: missing 'address' parameter");
        return;
    } else {
        $address = $params['address'];
    }

    $text = $address;

    // netscape and mozilla do not decode %40 (@) in BCC field (bug?)
    // so, don't encode it.
    $search = array('%40', '%2C');
    $replace  = array('@', ',');
    $mail_parms = array();
    foreach ($params as $var=>$value) {
        switch ($var) {
            case 'cc':
            case 'bcc':
            case 'followupto':
                if (!empty($value))
                    $mail_parms[] = $var.'='.str_replace($search,$replace,rawurlencode($value));
                break;

            case 'subject':
            case 'newsgroups':
                $mail_parms[] = $var.'='.rawurlencode($value);
                break;

            case 'extra':
            case 'text':
                $$var = $value;

            default:
        }
    }

    $mail_parm_vals = '';
    for ($i=0; $i<count($mail_parms); $i++) {
        $mail_parm_vals .= (0==$i) ? '?' : '&';
        $mail_parm_vals .= $mail_parms[$i];
    }
    $address .= $mail_parm_vals;

    $encode = (empty($params['encode'])) ? 'none' : $params['encode'];
    if (!in_array($encode,array('javascript','javascript_charcode','hex','none')) ) {
        die("mailto: 'encode' parameter must be none, javascript or hex");
        return;
    }

    if ($encode == 'javascript' ) {
     $sep	=	'&#x' . bin2hex("@").';';
      $text_arr	=	explode('@',$text);
      $text = implode('['.$sep.']',$text_arr)  ;
        $string = 'document.write(\'<a href="mailto:'.$address.'" '.$extra.'>\');';
        $string1 = 'document.write(\'</a> \');';
        $js_encode = '';
        for ($x=0; $x < strlen($string); $x++) {
            $js_encode .= '%' . bin2hex($string[$x]);
        }
     for ($x=0; $x < strlen($string1); $x++) {
            $js_encode1 .= '%' . bin2hex($string1[$x]);
        }
        $out	=	'<script type="text/javascript">eval(unescape(\''.$js_encode.'\'))</script>'.$text.'<script type="text/javascript">eval(unescape(\''.$js_encode1.'\'))</script>';

        return $out;

    } elseif ($encode == 'javascript_charcode' ) {
        $string = '<a href="mailto:'.$address.'" '.$extra.'>'.$text.'</a>';

        for($x = 0, $y = strlen($string); $x < $y; $x++ ) {
            $ord[] = ord($string[$x]);
        }

        $_ret = "<script type=\"text/javascript\" language=\"javascript\">\n";
        $_ret .= "<!--\n";
        $_ret .= "{document.write(String.fromCharCode(";
        $_ret .= implode(',',$ord);
        $_ret .= "))";
        $_ret .= "}\n";
        $_ret .= "//-->\n";
        $_ret .= "</script>\n";

        return $_ret;


    } elseif ($encode == 'hex') {

        preg_match('!^(.*)(\?.*)$!',$address,$match);
        if(!empty($match[2])) {
            die("mailto: hex encoding does not work with extra attributes. Try javascript.");
            return;
        }
        $address_encode = '';
        for ($x=0; $x < strlen($address); $x++) {
            if(preg_match('!\w!',$address[$x])) {
                $address_encode .= '%' . bin2hex($address[$x]);
            } else {
                $address_encode .= $address[$x];
            }
        }
        $text_encode = '';
        for ($x=0; $x < strlen($text); $x++) {
            $text_encode .= '&#x' . bin2hex($text[$x]).';';
        }

        $mailto = "&#109;&#97;&#105;&#108;&#116;&#111;&#58;";
        return '<a href="'.$mailto.$address_encode.'" '.$extra.'>'.$text_encode.'</a>';

    } else {
   		   $mailto = "&#109;&#97;&#105;&#108;&#116;&#111;&#58;";
        // no encoding
        $address_arr	=	explode("@",$address);
    $sep	=	'&#x' . bin2hex("@").';';
     $address	=	implode($sep,$address_arr);
     $text_arr	=	explode('@',$text);

     $text = implode('['.$sep.']',$text_arr)  ;
        return '<a href="'.$mailto.$address.'" '.$extra.'>'.$text.'</a>';

    }



}
      function entities($text){
     // var_dump(iconv_get_encoding('all'));
      $temp	=	array();
       	   for($k=0;$k<strlen($text);$k++){      	   if($text[$k]!="<"&&$text[$k]!=">"&&$text[$k]!="'"&&$text[$k]!='"'&&$text[$k]!="\\"&&$text[$k]!="="){      	   		$temp[$k]=mb_convert_encoding($text[$k],'cp1251','utf-8');
      	   		}
      	   else{      	   		$temp[$k]=mb_convert_encoding($text[$k],'cp1251','utf-8');
      	   		}      	   }
      	   return implode("",$temp);      }


    function addhits ($table, $id, $id_firld_name = 'id')
    {
      global $db;
      $query = 'UPDATE ' . my_sql::escape ($table) . ' SET hits=IF(hits > 0, hits + 1, 1)';
      $query .= ' WHERE ' . my_sql::escape ($id_firld_name) . '=\'' . my_sql::escape ($id) . '\'';
      return ($db->query ($query) ? TRUE : FALSE);
    }

	function true_xml($s=	''){
			$bad_s=	array(
				"�"=>"&laquo;",
				"�"=>"&lsaquo;",
				"�"=>"&raquo;",
				"�"=>"&rsaquo;",
				"�"=>"&bdquo;",
				"�"=>"&sbquo;",
				"�"=>"&ldquo;",
				"�"=>"&lsquo;",
				"?"=>"&#8219;",
				"�"=>"&rdquo;",
				"�"=>"&rsquo;",
				"\""=>"&quot;",
				"<"=>"&lt;",
				">"=>"&gt;",
				"&"=>"&amp;"
				);
		return str_replace(array_keys($bad_s),array_values($bad_s),$s);
	}
  }



  header ('Content-Type: text/html; charset=' . $NEW['pages_charset']);

  if (!$h['Host'])
  {
    $h['Host'] = $_SERVER['HTTP_HOST'];
  }

  $http_host = str_replace ('www.', '', strtolower ($h['Host']));
  $pos = strrpos ($http_host, ':');
  if (FALSE !== $pos)
  {
    $http_host = substr ($http_host, 0, $pos);
  }

  if (strlen ($http_host) - 1 == strrpos ('.', $http_host))
  {
    $http_host = substr ($http_host, 0, -1);
  }
  define ('T_BYFILE', 0);
  define ('T_BYVAR', 1);
  define ('TP_ROOTBLOCK', '_ROOT');
?>