Esempio n. 1
0
/**
 * Return file as response
 * @param $filePath path of file to return
 * @param $fileName name of file to return
 */
function forceDownload($filePath, $fileName)
{
    header("Cache-Control: private");
    header("Content-Description: File Transfer");
    header("Content-Disposition: attachment; filename=" . makeSafe(transliterate($fileName)));
    header("Content-Type: audio/mpeg");
    header("Content-length: " . filesize($filePath));
    readfile($filePath);
}
Esempio n. 2
0
 /**
  * Transform value into machine readable
  * 
  * @param string $value
  * @return string
  */
 function filter($value)
 {
     if ($value == '' && isset($this->element->form->elements->name)) {
         $value = transliterate($this->element->form->elements->name->value);
     } else {
         $value = transliterate($value);
     }
     $value = strtolower($value);
     return $value;
 }
Esempio n. 3
0
function CinemaNameByID($kinoid)
{
    global $tbl_cinemas;
    $q = "SELECT * FROM {$tbl_cinemas} WHERE ID={$kinoid}";
    $sqlres = mysql_query($q) or die(mysql_error() . " in SQL: {$q}");
    if (mysql_num_rows($sqlres) == 0) {
        return "";
    }
    $r = mysql_fetch_assoc($sqlres);
    mysql_free_result($sqlres);
    return stripslashes(transliterate($r['Cinema']));
}
Esempio n. 4
0
 public function filter($value)
 {
     if (function_exists('transliterate') && isset($_SERVER['SERVER_ADDR']) && $_SERVER['SERVER_ADDR'] == '192.168.0.10') {
         $filter[] = 'cyrillic_transliterate_bulgarian';
         $value = transliterate($value, $filter, 'utf-8', 'utf-8');
     }
     $value = strtolower(htmlentities($value, ENT_COMPAT, 'utf-8'));
     $value = preg_replace('/ß/', 'ss', $value);
     $value = preg_replace('/&(.)(uml);/', '$1e', $value);
     $value = preg_replace('/&(.)(acute|breve|caron|cedil|circ|dblac|die|dot|grave|macr|ogon|ring|tilde|uml);/', '$1', $value);
     $value = preg_replace('/([^a-z0-9\\-]+)/', '_', html_entity_decode($value));
     $value = trim($value, '_');
     return $value;
 }
Esempio n. 5
0
 /**
  * Filter
  *
  * @value
  */
 public function filter($value, $length = NULL)
 {
     // If field is empty
     if (!$value) {
         $value = cogear()->input->post('name');
     }
     // If even $_POST['name'] doesn't exist
     if (!$value) {
         return;
     }
     $value = transliterate($value);
     // Filter for all unsafe chars
     $value = preg_replace('#([^' . config('form.filter.uri.pattern', '\\w\\._-') . '])#', '-', $value);
     // Replace ----- with single - and trim - by sides
     $value = trim(preg_replace('#([-]{2,})#', '-', $value), '-');
     $length or $length = config('form.filter.uri.maxlength', 15);
     if ($length) {
         $value = substr($value, 0, $length);
     }
     return $value;
 }
Esempio n. 6
0
<?php

# транслитерация строк, можно поугарать с выводом
function transliterate($st)
{
    $st = strtr($st, "абвгдежзийклмнопрстуфыэАБВГДЕЖЗИЙКЛМНОПРСТУФЫЭ", "abvgdegziyklmnoprstufieABVGDEGZIYKLMNOPRSTUFIE");
    $st = strtr($st, array('ё' => "yo", 'х' => "h", 'ц' => "ts", 'ч' => "ch", 'ш' => "sh", 'щ' => "shch", 'ъ' => "", 'ь' => "", 'ю' => "yu", 'я' => "ya", 'Ё' => "Yo", 'Х' => "H", 'Ц' => "Ts", 'Ч' => "Ch", 'Ш' => "Sh", 'Щ' => "Shch", 'Ъ' => "", 'Ь' => "", 'Ю' => "Yu", 'Я' => "Ya"));
    return $st;
}
echo transliterate("Шмисечка!!! Я тебя люблю!!!");
$html = file_get_html("http://dynamo.kiev.ua/comp/ukraine/table/");
//Ищем названия клубов + общее количество очков.Сохраняем в массив
foreach ($html->find("tbody tr") as $tr) {
    //Текущие очки
    $point = $tr->find("td", 7)->plaintext;
    //Название клуба
    foreach ($tr->find(".table-championship__link strong") as $i) {
        $teams[transliterate($i->plaintext)]["name"] = $i->plaintext;
        $teams[transliterate($i->plaintext)]["point"] = $point;
    }
}
//Ищем превью.Сохраняем файлы и ссылки.
foreach ($html->find(".table-championship__img img") as $i) {
    $path = "img/" . transliterate($i->alt) . ".png";
    $url = "http://dynamo.kiev.ua/" . $i->src;
    file_put_contents($path, file_get_contents($url));
    $links_for_teams_preview[transliterate($i->alt)] = $path;
}
//Результаты последнего тура
for ($i = 0; $i < 7; $i++) {
    //Парсим "хозяев","гостей" и итоговый счет.
    $master = $html->find(".tour ul li .left strong", $i);
    $guest = $html->find(".tour ul li .right strong", $i);
    $count = $html->find(".tour ul li .count", $i);
    $last_tour_results[$i]["master"] = transliterate($master->plaintext);
    $last_tour_results[$i]["guest"] = transliterate($guest->plaintext);
    $last_tour_results[$i]["count"] = trim($count->plaintext);
}
//Очищаем память
$html->clear();
unset($html);
Esempio n. 8
0
 /**
  * Создание меню
  * @param $data array - $_POST массив с параметрами
  * @return string
  */
 public function create_menu($data)
 {
     //Создание имени шаблона
     $tpl_name = strtolower(transliterate($data['menu_name']));
     $tpl_name = str_replace(array(' ', '-', ',', '.'), '_', $tpl_name);
     $tpl_file = 'application/views/templates/menus/' . $tpl_name . '.tpl';
     if (file_exists($tpl_file)) {
         $tpl_file = 'application/views/templates/menus/' . $tpl_name . '_' . time() . '.tpl';
     }
     switch ($data['typeMenu']) {
         case "1":
             $type_menu = 'tabs';
             //     $menu_content = $this->create_tab_menu_tpl($data, $tpl_name, $tpl_file);
             $menu_content = $this->create_tab_menu_tpl($data, $tpl_name);
             break;
         case "2":
             $type_menu = 'pills';
             //     $menu_content = $this->create_pills_menu_tpl($data, $tpl_name, $tpl_file);
             $menu_content = $this->create_pills_menu_tpl($data, $tpl_name);
             break;
         default:
             exit("Не определен тип меню");
     }
     $handle = fopen($tpl_file, "w");
     fwrite($handle, $menu_content);
     fclose($handle);
     //Запись в БД
     $params = array('name_menu' => $data['menu_name'], 'type_menu' => $type_menu, 'class_menu' => $data['menu_class'], 'tpl_file' => $tpl_file);
     $menu_id = $this->db->sql_execute($this->sql_create_menu, $params);
     if (!$menu_id) {
         exit('Не удалось создать меню');
     }
     foreach ($data['sections'] as $item) {
         $params = array('fid_menu' => $menu_id, 'name_section' => $item['section_name'], 'fid_record' => $item['fid_record'], 'sort_section' => $item['section_sort'], 'fid_rt' => $item['request_type'], 'html_id' => $item['html_id']);
         $result = $this->db->sql_execute($this->sql_create_section, $params);
         if (!$result) {
             exit('Не удалось создать раздел');
         }
     }
     return true;
 }
Esempio n. 9
0
        }
    }
}
if ($user['LINKED_OBJECT'] && !$location_found) {
    setGlobal($user['LINKED_OBJECT'] . '.seenAt', '');
}
$sqlQuery = "SELECT *, DATE_FORMAT(ADDED, '%H:%i') as DAT\n               FROM shouts\n              ORDER BY ADDED DESC\n              LIMIT 1";
$tmp = SQLSelectOne($sqlQuery);
if (!headers_sent()) {
    header("HTTP/1.0: 200 OK\n");
    header('Content-Type: text/html; charset=utf-8');
}
if (defined('BTRACED')) {
    echo "OK";
} elseif ($tmp['MESSAGE'] != '') {
    echo ' ' . $tmp['DAT'] . ' ' . transliterate($tmp['MESSAGE']);
}
// closing database connection
$db->Disconnect();
endMeasure('TOTAL');
// end calculation of execution time
/**
 * Calculate distance between two GPS coordinates
 * @param mixed $latA First coord latitude
 * @param mixed $lonA First coord longitude
 * @param mixed $latB Second coord latitude
 * @param mixed $lonB Second coord longitude
 * @return double
 */
function calculateTheDistance($latA, $lonA, $latB, $lonB)
{
Esempio n. 10
0
        }
        if ($_SESSION['tgt'] == "oriya") {
            unset($_SESSION['yayya']);
            unset($_SESSION['wava']);
        }
        if ($_SESSION['tgt'] == "assamese") {
            unset($_SESSION['aconyab']);
        }
    }
}
$op = "";
// Echo output is buffered into this variable
// do missing case scenarious
require "./diCrunch/diCrunch_charsets.php";
require "./diCrunch/diCrunch_preprocess.php";
$text = transliterate($text, $_SESSION['src'], $_SESSION['tgt']);
// Transliterate the Inputbox Text
$langtag = array('tamil' => 'dtamil', 'iast' => 'unicode', 'iso' => 'unicode2', 'harvard-kyoto' => 'hk');
foreach ($langtag as $collang => $syslang) {
    if ($_SESSION['src'] == $syslang) {
        $_SESSION['src'] = $collang;
    }
    if ($_SESSION['tgt'] == $syslang) {
        $_SESSION['tgt'] = $collang;
    }
}
$XML = <<<CWS
<?xml version="1.0" encoding="utf-8" ?>
<data>
<source script="{$_SESSION['src']}">{$tmp}</source>
<target script="{$_SESSION['tgt']}">{$text}</target>
Esempio n. 11
0
/**
 * Transliterates non ASCII chars to ASCII.
 * This is an approximation.
 *
 * Note: Performance and accuracy is gained if the pecl translit extension is available.
 * @see http://pecl.php.net/package/translit
 *
 * @param	string String to transliterate
 * @return	string
 */
function to_ascii($str)
{
	if (!$str)
    {
    	return;
    }

    if (function_exists('transliterate'))
    {
    	return transliterate($str, array('normalize_ligature'), 'ISO-8859-1', 'ISO-8859-1');
    }

	static $lookup = array(
		'&Agrave;' => 'A',
		'&Aacute;' => 'A',
		'&Acirc;' => 'A',
		'&Atilde;' => 'A',
		'&Auml;' => 'AE',
		'&Aring;' => 'A',
		'&AElig;' => 'AE',
		'&Ccedil;' => 'C',
		'&Egrave;' => 'E',
		'&Eacute;' => 'E',
		'&Ecirc;' => 'E',
		'&Euml;' => 'E',
		'&Igrave;' => 'I',
		'&Iacute;' => 'I',
		'&Icirc;' => 'I',
		'&Iuml;' => 'I',
		'&ETH;' => 'Dj',
		'&Ntilde;' => 'N',
		'&Ograve;' => 'O',
		'&Oacute;' => 'O',
		'&Ocirc;' => 'O',
		'&Otilde;' => 'O',
		'&Ouml;' => 'OE',
		'&Oslash;' => 'U',
		'&Ugrave;' => 'U',
		'&Uacute;' => 'U',
		'&Ucirc;' => 'U',
		'&Uuml;' => 'UE',
		'&Yacute;' => 'Y',
		'&THORN;' => 'Th',
		'&szlig;' => 'ss',
		'&agrave;' => 'a',
		'&aacute;' => 'a',
		'&acirc;' => 'a',
		'&atilde;' => 'a',
		'&auml;' => 'ae',
		'&aring;' => 'a',
		'&aelig;' => 'ae',
		'&ccedil;' => 'c',
		'&egrave;' => 'e',
		'&eacute;' => 'e',
		'&ecirc;' => 'e',
		'&euml;' => 'e',
		'&igrave;' => 'i',
		'&iacute;' => 'i',
		'&icirc;' => 'i',
		'&iuml;' => 'i',
		'&eth;' => 'dj',
		'&ntilde;' => 'n',
		'&ograve;' => 'o',
		'&oacute;' => 'o',
		'&ocirc;' => 'o',
		'&otilde;' => 'o',
		'&ouml;' => 'oe',
		'&oslash;' => 'o',
		'&ugrave;' => 'u',
		'&uacute;' => 'u',
		'&ucirc;' => 'u',
		'&uuml;' => 'ue',
		'&yacute;' => 'y',
		'&thorn;' => 'th',
		'&yuml;' => 'y'
	);

    $str = htmlentities($str);
    $str = str_replace(array_keys($lookup), array_values($lookup), $str);
    $str = html_entity_decode($str);
    $str = preg_replace('#[^a-z0-9]+#i', '-', $str);

    return $str;
}
Esempio n. 12
0
$template->assign('display_mode', $page['display_mode']);
// find all tags available for the current user
$tags = get_available_tags();
// +-----------------------------------------------------------------------+
// |                       letter groups construction                      |
// +-----------------------------------------------------------------------+
if ($page['display_mode'] == 'letters') {
    // we want tags diplayed in alphabetic order
    usort($tags, 'tag_alpha_compare');
    $current_letter = null;
    $nb_tags = count($tags);
    $current_column = 1;
    $current_tag_idx = 0;
    $letter = array('tags' => array());
    foreach ($tags as $tag) {
        $tag_letter = mb_strtoupper(mb_substr(transliterate($tag['name']), 0, 1, PWG_CHARSET), PWG_CHARSET);
        if ($current_tag_idx == 0) {
            $current_letter = $tag_letter;
            $letter['TITLE'] = $tag_letter;
        }
        //lettre precedente differente de la lettre suivante
        if ($tag_letter !== $current_letter) {
            if ($current_column < $conf['tag_letters_column_number'] and $current_tag_idx > $current_column * $nb_tags / $conf['tag_letters_column_number']) {
                $letter['CHANGE_COLUMN'] = true;
                $current_column++;
            }
            $letter['TITLE'] = $current_letter;
            $template->append('letters', $letter);
            $current_letter = $tag_letter;
            $letter = array('tags' => array());
        }
Esempio n. 13
0
        exit;
    }
    //*/
}
setcookie("kinobg-grad", $grad);
setcookie("kinobg-izbrangrad", "");
setcookie("kinobg-kino", "");
$_SESSION['grad'] = $grad;
$sqlres = mysql_query("SELECT * FROM {$tbl_cinemas} WHERE CityID={$grad} ORDER BY Priority ") or die(mysql_error());
echo "<?xml version=\"1.0\"?>\n<!DOCTYPE wml PUBLIC \"-//WAPFORUM//DTD WML 1.1//EN\" \"http://www.wapforum.org/DTD/wml_1.1.xml\">\n";
echo "<wml>\n";
$gradname = CityNameByID($grad);
echo "<template>Izbor na kino</template>\n";
echo "<card id=\"kina\" title=\"{$gradname}\">\n";
////echo '<do type="accept" label="izberi"><go href="filmi.php"><postfield name="kino" value="$(kino)"/></go></do>';
echo "<p>{$template_header} <br/>\n <a href=\"{$page_grad}?grad={$grad}\">promiana grad</a></p>\n";
echo "<p>\n";
echo "<b>Izberete kino:</b>\n";
echo "<select name=\"kino\" ivalue=\"0\">\n";
//echo "<postfield name=\"kino\" value=$(kino)/>\n";
while ($r = mysql_fetch_assoc($sqlres)) {
    $kinoid = $r['ID'];
    if (NumberOfMovies($kinoid) > 0) {
        echo "<option value=\"" . $kinoid . "\" onpick=\"filmi.php?kino=\$(kino)\">" . stripslashes(transliterate($r['Cinema'])) . "</option>\n";
    }
}
echo "</select>\n";
//*/
echo "</p>\n";
echo "</card>\n";
echo "</wml>";
Esempio n. 14
0
 /**
  * Transliterates characters in a given string where possible.
  *
  * @param string $string      String containing characters to
  *        transliterate
  * @param string $charsetFrom Optional character set of the string,
  *        defaults to UTF-8
  * @param string $charsetTo   Optional character set to which the string
  *        should be converted, defaults to ISO-8859-1
  *
  * @return string String with characters transliterated or the original
  *         string if transliteration was not possible
  */
 public function transliterate($string, $charsetFrom = 'UTF-8', $charsetTo = 'ISO-8859-1')
 {
     // @link http://pecl.php.net/package/translit
     if (function_exists('transliterate')) {
         $string = transliterate($string, array('han_transliterate', 'diacritical_remove'), $charsetFrom, $charsetTo);
     } elseif (function_exists('iconv')) {
         $string = iconv($charsetFrom, $charsetTo . '//TRANSLIT', $string);
     } else {
         // @link http://stackoverflow.com/questions/1284535/php-transliteration/1285491#1285491
         $string = preg_replace('~&([a-z]{1,2})(acute|cedil|circ|grave|lig|orn|ring|slash|th|tilde|uml);~i', '$1', htmlentities($string, ENT_COMPAT, $charsetFrom));
     }
     return $string;
 }
Esempio n. 15
0
    //$film = $agendaid;
}
mysql_free_result($sqlFilm);
//$film = transliterate($r['Cinema']);
echo "<card title='Kino: {$kinoname}'>";
echo "<p>{$template_header} <br/> <a href='kino.php?grad={$grad}'>izbor kina</a></p>";
echo "<p>";
if (!isset($sqlres) || mysql_num_rows($sqlres) == 0) {
    //no movies this week :)
    var_dump($_REQUEST);
    echo "Niama informacia za filma v momenta. Molia, opitajte po-kysno.";
} else {
    echo "Film: {$film}</p><p>";
    echo "Ot data: {$from}</p><p>";
    $r = mysql_fetch_assoc($sqlres);
    echo transliterate($r['Agenda']);
    /*echo '<do type="accept" label="izberi">';
       echo '<go href="film.php"><postfield name="" value="$(film)"/></go>';
       echo '</do>';
    
       echo "Izberete film:";
       echo "<select name=\"film\" ivalue=\"0\">";
    
       echo "<option value='0' selected='selected'>-Izbor kina-</option>";
       
       while( $r = mysql_fetch_assoc($sqlres) )
       {
          //var_dump($r);
          if($r['Type']=='list')
          {
             //var_dump($r);
Esempio n. 16
0
/**
 * Make string clear, for file system file name
 *
 * @param  (string) (str) Input string
 * @return (string)
 */
function makeStringSafe($str)
{
    return trim(str_replace(array('  '), array(' '), preg_replace('/[^a-zA-Z0-9_ %\\[\\]\\.\\(\\)%&-]/s', '', remove_accents(transliterate($str)))));
}
Esempio n. 17
0
        </div>
        <div class="col-xs-2">  <!-- [drop down country ] -->
            <select id="country" class="combobox text2" disabled="disabled">
                <option value="0"><?php 
echo dic("Tracking.Country");
?>
</option>
                <?php 
$ds3 = query("select * from countries order by name");
while ($dr = pg_fetch_array($ds3)) {
    ?>
                        <option value="<?php 
    echo $dr["id"];
    ?>
"><?php 
    echo transliterate($dr["name"], $cLang);
    ?>
</option>
                <?php 
}
?>
            </select>
        </div>
        <div class="col-xs-2">  <!-- [labela date time] -->
            <?php 
strtoupper(dic("Settings.TimeFormat"));
?>
        </div>
        <div class="col-xs-3">  <!-- [drop down date time] -->
            <select id="cbDate" class="combobox text2">
                <?php 
Esempio n. 18
0
<?require_once($_SERVER['DOCUMENT_ROOT'].'/bitrix/modules/main/include/prolog_before.php');

$file_name = transliterate($_REQUEST['file_name']);
$file_name_ex = explode('.',$file_name);
$x = $_REQUEST['x'];
$y = $_REQUEST['y'];
$w = $_REQUEST['width'];
$h = $_REQUEST['height'];

    //print_r($file_name);
    //обрезка и сохранение на сервере
    /*$src = imagecreatefromjpeg('/images/uploads/153225000_698c62c38a_o.jpg');
    $dest = imagecreatetruecolor($w, $h);

    // Копирование
    imagecopy($dest, $src, $x, $y, $w, $h, $w, $h);
        
    // Вывод и освобождение памяти
    //header('Content-Type: image/*');
    imagejpeg($dest,'avatar.jpg', 90);*/
        
    /*imagedestroy($dest);
    imagedestroy($src);*/
    if($file_name_ex[1] == 'jpg' || $file_name_ex[1] == 'jpeg' || $file_name_ex[1] == 'JPG' || $file_name_ex[1] == 'JPEG')
    {
    	$targ_w = $targ_h = 140;
    	$jpeg_quality = 100;
    	$img_r = imagecreatefromjpeg("../images/uploads/".$file_name);
    	$dst_r = ImageCreateTrueColor($targ_w, $targ_h);
    	imagecopyresampled($dst_r,$img_r,0,0,$x,$y,$targ_w,$targ_h,$w,$h);
    	imagejpeg($dst_r, "../images/avatar/av_".$file_name, $jpeg_quality);
Esempio n. 19
0
/**
 * Callback used for sorting by name (slug) with cache.
 */
function tag_alpha_compare($a, $b)
{
    global $cache;
    foreach (array($a, $b) as $tag) {
        if (!isset($cache[__FUNCTION__][$tag['name']])) {
            $cache[__FUNCTION__][$tag['name']] = transliterate($tag['name']);
        }
    }
    return strcmp($cache[__FUNCTION__][$a['name']], $cache[__FUNCTION__][$b['name']]);
}
Esempio n. 20
0
    $audioId = "";
    //clear string
    if (startsWith($ownerId, "-")) {
        $ownerId = substr($ownerId, 1);
        $audioId = "-";
    }
    $audioId .= decode($ownerId) . "_" . decode($aid);
}
$audioGetUrl = "https://api.vk.com/method/audio.getById?audios=" . $audioId . "&access_token=" . $token;
$response = file_get_contents($audioGetUrl);
$json = json_decode($response, true);
if (empty($json['response'])) {
    notFound();
}
$audio = $json['response'][0];
$filename = makeSafe(transliterate($audio["artist"] . " - " . $audio["title"] . ".mp3"));
$audioUrl = $audio["url"];
$fullpath = "dl/" . $filename;
if (file_exists($fullpath)) {
    forceDownload($fullpath, $filename);
} else {
    if (downloadFile($audioUrl, $fullpath)) {
        forceDownload($fullpath, $filename);
    }
}
function notFound()
{
    header('HTTP/1.0 404 Not Found');
    readfile("/home/alashov/www/.config/404.html");
    exit;
}
Esempio n. 21
0
<?php

## Транслитерация строк.
function transliterate($st)
{
    $st = strtr($st, "абвгдежзийклмнопрстуфыэАБВГДЕЖЗИЙКЛМНОПРСТУФЫЭ", "abvgdegziyklmnoprstufyeABVGDEGZIYKLMNOPRSTUFYE");
    $st = strtr($st, array('ё' => "yo", 'х' => "h", 'ц' => "ts", 'ч' => "ch", 'ш' => "sh", 'щ' => "shch", 'ъ' => '', 'ь' => '', 'ю' => "yu", 'я' => "ya", 'Ё' => "Yo", 'Х' => "H", 'Ц' => "Ts", 'Ч' => "Ch", 'Ш' => "Sh", 'Щ' => "Shch", 'Ъ' => '', 'Ь' => '', 'Ю' => "Yu", 'Я' => "Ya"));
    return $st;
}
echo transliterate("У попа была собака, он ее любил.");
Esempio n. 22
0
//bootstrap the forum; you should read that file first
require_once './start.php';
//get page number
define('PAGE', preg_match('/^[1-9][0-9]*$/', @$_GET['page']) ? (int) $_GET['page'] : 1);
//submitted info for making a new thread
//(name / password already handled in 'start.php')
define('TITLE', safeGet(@$_POST['title'], SIZE_TITLE));
define('TEXT', safeGet(@$_POST['text'], SIZE_TEXT));
/* ======================================================================================================================
   new thread submitted
   ====================================================================================================================== */
//has the user submitted a new thread?
//(`AUTH` will be true if username and password submitted and correct, `TITLE` and `TEXT` are checked to not be blank)
if (CAN_POST && AUTH && TITLE && TEXT) {
    //the file on disk is a simplified version of the title:
    $translit = preg_replace(array('/[^_a-z0-9-]/i', '/_{2,}/'), '_', str_replace(array("'", "`", "^", "~", "'", '"'), '', strtolower(iconv('UTF-8', 'US-ASCII//IGNORE//TRANSLIT', transliterate(TITLE)))));
    //old iconv versions and certain inputs may cause a nullstring. don't allow a blank filename
    if (!$translit) {
        $translit = '_';
    }
    //if a thread already exsits with that name, append a number until an available filename is found
    $c = 0;
    do {
        $file = $translit . ($c++ ? '_' . ($c - 1) : '');
    } while (file_exists("{$file}.rss"));
    //write out the new thread as an RSS file:
    $rss = new DOMTemplate(FORUM_ROOT . '/lib/rss-template.xml');
    $rss->set(array('/rss/channel/title' => TITLE, '/rss/channel/link' => FORUM_URL . PATH_URL . $file, '/rss/channel/item/title' => TITLE, '/rss/channel/item/link' => FORUM_URL . PATH_URL . "{$file}#" . base_convert(microtime(), 10, 36), '/rss/channel/item/author' => NAME, '/rss/channel/item/pubDate' => gmdate('r'), '/rss/channel/item/description' => formatText(TEXT)));
    file_put_contents("{$file}.rss", $rss->html()) or die("Failed to save thread. Folder permissions may be incorrect.");
    //regenerate the folder's RSS file
    indexRSS();
Esempio n. 23
0
<?php

$uploaddir = $_SERVER['DOCUMENT_ROOT'] . '/images/uploads/';
//print_r($_FILES, true);
if (move_uploaded_file($_FILES['work-avatar']['tmp_name'], $uploaddir . transliterate($_FILES['work-avatar']['name']))) {
    print "File is valid, and was successfully uploaded.";
} else {
    print "There some errors!";
}
function transliterate($input)
{
    $gost = array("а" => "a", "б" => "b", "в" => "v", "г" => "g", "д" => "d", "е" => "e", "ё" => "e", "ж" => "zh", "з" => "z", "и" => "i", "й" => "y", "к" => "k", "л" => "l", "м" => "m", "н" => "n", "о" => "o", "п" => "p", "р" => "r", "с" => "s", "т" => "t", "у" => "u", "ф" => "f", "х" => "kh", "ц" => "ts", "ч" => "ch", "ш" => "sh", "щ" => "shch", "ы" => "y", "э" => "e", "ю" => "yu", "я" => "ya", "А" => "A", "Б" => "B", "В" => "V", "Г" => "G", "Д" => "D", "Е" => "E", "Ё" => "E", "Ж" => "Zh", "З" => "Z", "И" => "I", "Й" => "Y", "К" => "K", "Л" => "L", "М" => "M", "Н" => "N", "О" => "O", "П" => "P", "Р" => "R", "С" => "S", "Т" => "T", "У" => "U", "Ф" => "F", "Х" => "Kh", "Ц" => "Ts", "Ч" => "Ch", "Ш" => "Sh", "Щ" => "Shch", "Ы" => "Y", "Э" => "E", "Ю" => "Yu", "Я" => "Ya", "Ъ" => "", "ъ" => "", "ь" => "", "Ь" => "", " " => "_", "," => "_", "_" => "_");
    return strtr($input, $gost);
}
//echo 'Contents of $_FILES:<br/><pre>'.print_r($_FILES,true).'</pre>';
Esempio n. 24
0
         $errordata[] = "Дубликат HOST";
         $key[] = "host";
         $ek["host"] = true;
     }
     $lS2 = free_ips($_POST['room']);
     // $_POST['F']	 	=  ($_POST['F']);
     // $_POST['I']	 	=  ($_POST['I']);
     // $_POST['O']	  	=  ($_POST['O']);
     // $_POST['department'] =  ($_POST['department']);
     // $_POST['comment']	 =  ($_POST['comment']);
     $content .= cut($_POST, $lS2);
 } else {
     $exnet = explode(".", $_POST['ip']);
     $n = 'net' . $exnet[2];
     if (strlen($_POST['host']) < 2) {
         $host = transliterate($_POST['F']) . "_" . random_chars(2);
     } else {
         $host = $_POST['host'];
     }
     $ss = explode(".", $_POST['ip']);
     $IArray = array('active' => '1', 'F' => $_POST['F'], 'I' => $_POST['I'], 'O' => $_POST['O'], 'date' => $_POST['date'], 'host' => $host, 'room' => $_POST['room'], 'mac' => strtolower($_POST['mac']), 'ip' => $_POST['ip'], 'tel' => $_POST['tel'], 'kurs' => $_POST['kurs'], 'department' => $_POST['department'], 'comment' => $_POST['comment'], 's_net' => $ss[2], 's_ip' => $ss[3], 'admin' => ADMINLOGIN);
     if ((LEVEL == 1 or LEVEL == 2) && defined('ALLOW_users_isrouter') && ALLOW_users_isrouter == true) {
         $IArray['isrouter'] = $_POST['isrouter'] == 'on' ? 1 : 0;
     }
     if (LEVEL == 1 or LEVEL == 2) {
         $IArray['active'] = $_POST['active'];
     }
     if (defined('ALLOW_users_cosmosedit') && ALLOW_users_cosmosedit == true) {
         $IArray['idc'] = $_POST['idc'];
     }
     if (!$dataMySQL->Insert($IArray, DB_PREFIX . "users")) {
Esempio n. 25
0
        header("Location: kino.php?grad=" . $_COOKIE['kinobg-grad']);
        exit;
    } else {
        $grad = '';
    }
}
$sqlres = mysql_query("SELECT * FROM {$tbl_cities} WHERE Active='yes' ORDER BY Priority ") or die(mysql_error());
echo "<?xml version=\"1.0\"?>\n<!DOCTYPE wml PUBLIC \"-//WAPFORUM//DTD WML 1.1//EN\" \"http://www.wapforum.org/DTD/wml_1.1.xml\">";
echo "\n<wml>\n";
echo "<template>{$template_header}</template>";
echo "<card id=\"c1\" title=\"wap.kinobg.com\">\n";
$select_body = '';
$default_grad = '';
$i = 0;
while ($r = mysql_fetch_assoc($sqlres)) {
    //var_dump($r);
    if ($r['ID'] == $grad) {
        $default_grad = $i;
    }
    $select_body .= '<option value="' . $r['ID'] . '" onpick="kino.php?grad=$(grad)">' . transliterate($r['City']) . "</option>\n";
    $i++;
}
echo "<p>";
echo "Izberete grad:<br/>";
echo "<select name=\"grad\" value=\"{$default_grad}\">\n";
echo $select_body;
echo "</select>";
//*/
echo "</p>";
echo "</card>";
echo "</wml>";
Esempio n. 26
0
function getPilotRealName($pilotIDview, $serverID, $getAlsoCountry = 0, $getAlsoExternalIndicator = 1, $gender = 1)
{
    global $db, $pilotsTable, $opMode;
    global $currentlang, $nativeLanguage, $langEncodings, $lang2iso, $langEncodings;
    global $countries, $langEncodings;
    global $CONF_use_leonardo_names, $PREFS, $CONF, $moduleRelPath;
    # martin jursa may 2008:
    # make the function error-tolerant, in case $pilotIDview is submitted in the form [serverid]_[userid]
    if (strpos($pilotIDview, '_') !== false) {
        $parts = explode('_', $pilotIDview);
        $pilotIDview = $parts[1];
        $serverID = $parts[0];
    }
    if ($PREFS->nameOrder == 1) {
        $nOrder = "CONCAT(FirstName,' ',LastName)";
        $nOrderEn = "CONCAT(FirstNameEn,' ',LastNameEn)";
    } else {
        $nOrder = "CONCAT(LastName,' ',FirstName)";
        $nOrderEn = "CONCAT(LastNameEn,' ',FirstNameEn)";
    }
    $query = "SELECT {$nOrder} as realName ,{$nOrderEn} as realNameEn, countryCode,serverID,Sex FROM {$pilotsTable} WHERE pilotID={$pilotIDview}  AND serverID={$serverID}";
    $res = $db->sql_query($query);
    // echo $query;
    // Get real name from leonardo_pilots
    //
    // we must make sure the name can be displayed in the $currentlang encoding
    //
    if ($res) {
        $pilot = $db->sql_fetchrow($res);
        $realName = $pilot['realName'];
        $realNameEn = $pilot['realNameEn'];
        $pilotCountry = strtolower($pilot['countryCode']);
        if (strlen($realName) > 1 && ($CONF_use_leonardo_names || $langEncodings[$currentlang] == $langEncodings[$nativeLanguage])) {
            // always return real name
            $str = $realName;
            // we have some info on how to tranlitarate
            // and the currentlang is not the native lang of the pilot.
            $pilotLang = "";
            if ($pilotCountry && !countryHasLang($pilotCountry, $currentlang)) {
                if (($pilotLang = array_search($pilotCountry, $lang2iso)) === NULL) {
                    $pilotLang = $nativeLanguage;
                }
                //echo $pilotLang."#".$pilotCountry."$";
            }
            //	if all else fails translitarate using the nativeLangauge
            if (!$pilotCountry && !$pilotLang && $langEncodings[$nativeLanguage] != $langEncodings[$currentlang]) {
                $pilotLang = $nativeLanguage;
            }
            // echo ">$realName#$pilotLang#$pilotCountry#<br>";
            $enc = $langEncodings[$pilotLang];
            if ($enc) {
                if (strlen($realNameEn) > 1) {
                    $str = $realNameEn;
                } else {
                    $str = transliterate($str, $enc);
                }
            }
            //echo $realName."@";
            // else return as is.
            if ($getAlsoCountry) {
                $str = getNationalityDescription($pilot['countryCode'], 1, 0) . $str;
            }
            if ($gender == 1 && strtoupper($pilot['Sex']) == 'F' && $getAlsoCountry) {
                // the $getAlsoCountry will prevent putting the F symbol in sync-log
                $str .= leoHtml::img("icon_female_small.gif", 0, 0, 'absmiddle', '', 'icons1');
            }
            $str = $str . getExternalLinkIconStr($serverID, '', $getAlsoExternalIndicator);
            return $str;
        }
        /*
        		if (strlen ($realName)>1) && $currentlang==$nativeLanguage) { // else realname is no good
        			if ($getAlsoCountry ) return getNationalityDescription($pilot['countryCode'],1,0)."$realName";
        			else return $realName;
        		}*/
    }
    if ($opMode == 1) {
        // phpNuke
        $res = $db->sql_query("SELECT username,name FROM " . $CONF['userdb']['users_table'] . " WHERE " . $CONF['userdb']['user_id_field'] . "=" . $pilotIDview);
        if ($res) {
            $row = $db->sql_fetchrow($res);
            if ($currentlang != $nativeLanguage) {
                $realName = $row["username"];
            } else {
                if ($row["name"] != '') {
                    $realName = $row["name"];
                } else {
                    $realName = $row["username"];
                }
            }
            $str = $realName;
        }
    } else {
        // phpBB
        $res = $db->sql_query("SELECT " . $CONF['userdb']['user_real_name_field'] . " FROM  " . $CONF['userdb']['users_table'] . " WHERE " . $CONF['userdb']['user_id_field'] . "=" . $pilotIDview);
        if ($res) {
            $row = $db->sql_fetchrow($res);
            $realName = $row[$CONF['userdb']['user_real_name_field']];
            $str = $realName;
            // we have some info on how to tranlitarate
            // and the currentlang is not the native lang of the pilot.
            $pilotLang = "";
            if ($pilotCountry && !countryHasLang($pilotCountry, $currentlang)) {
                if (($pilotLang = array_search($pilotCountry, $lang2iso)) === NULL) {
                    $pilotLang = $nativeLanguage;
                }
                //echo $pilotLang."#".$pilotCountry."$";
            }
            //	if all else fails translitarate using the nativeLangauge
            if (!$pilotCountry && !$pilotLang && $langEncodings[$nativeLanguage] != $langEncodings[$currentlang]) {
                $pilotLang = $nativeLanguage;
            }
            // echo "($str)>".$pilotLang."#".$pilotCountry."$";
            $enc = $langEncodings[$pilotLang];
            if ($enc) {
                if (strlen($realNameEn) > 1) {
                    $str = $realNameEn;
                } else {
                    $str = transliterate($str, $enc);
                }
            }
            //echo $realName."@";
            // else return as is.
        }
    }
    $str .= getExternalLinkIconStr($serverID, '', $getAlsoExternalIndicator);
    if ($getAlsoCountry) {
        $str = getNationalityDescription($pilot['countryCode'], 1, 0) . $str;
    }
    if ($gender == 1 && strtoupper($pilot['Sex']) == 'F' && $getAlsoCountry) {
        // the $getAlsoCountry will prevent putting the F symbol in sync-log
        $str .= leoHtml::img("icon_female_small.gif", 0, 0, 'absmiddle', '', 'icons1');
    }
    return $str;
}
Esempio n. 27
0
/**
 * simplify a string to insert it into an URL
 *
 * @param string $str
 * @return string
 */
function str2url($str)
{
    $str = $safe = transliterate($str);
    $str = preg_replace('/[^\\x80-\\xffa-z0-9_\\s\'\\:\\/\\[\\],-]/', '', $str);
    $str = preg_replace('/[\\s\'\\:\\/\\[\\],-]+/', ' ', trim($str));
    $res = str_replace(' ', '_', $str);
    if (empty($res)) {
        $res = str_replace(' ', '_', $safe);
    }
    return $res;
}
Esempio n. 28
0
        $onpick = 'onpick="film.php?kino=' . $kinoid . '&amp;film=$(film)"';
        if ($r['Type'] == 'list') {
            //var_dump($r);
            $filmid = $r['Film'];
            //avoid repeatance
            if (isset($added[$filmid])) {
                continue;
            }
            $added[$filmid] = true;
            $q = "SELECT * FROM {$tbl_film_info} WHERE ID={$filmid}";
            $filmres = mysql_query($q) or die(mysql_error());
            if (mysql_num_rows($filmres) == 0) {
                die("no movie {$filmid}");
            }
            $film = mysql_fetch_assoc($filmres);
            $title = transliterate($film['Title']);
            echo "<option value='{$agendaid}' {$onpick}>{$title}" . "</option>";
            mysql_free_result($filmres);
        } else {
            if ($r['Type'] == 'raw') {
                $title = stripslashes(transliterate($r['Film']));
                echo "<option value='{$agendaid}' {$onpick}>{$title}</option>";
            }
        }
    }
    mysql_free_result($sqlres);
    echo "</select>";
}
echo "</p>";
echo "</card>";
echo "</wml>";
Esempio n. 29
0
 $series = array();
 if ($protocol == 'custom') {
     $rtsp_url = @trim($_POST['rtsp_url']);
     $tmp_arr = array();
     if (preg_match("/s\\d+e(\\d+).*\$/i", $rtsp_url, $tmp_arr)) {
         $series = range(1, (int) $tmp_arr[1], 1);
     }
 } else {
     $rtsp_url = '';
 }
 $status = $rtsp_url ? 1 : 0;
 if (!empty($_GET['id'])) {
     $video = Video::getById($_GET['id']);
 }
 if (@$_GET['save']) {
     $trans_name = transliterate(@urldecode($_POST['name']));
     if ($hd) {
         $trans_name .= '_HD';
     }
     $existed = Mysql::getInstance()->from('video')->where(array('path' => $trans_name))->get()->first();
     if (!empty($existed)) {
         $error = _('Error: The folder with that name already exists');
     }
     if (@$_GET['name'] && !$error) {
         $master = new VideoMaster();
         try {
             $master->createMediaDir($trans_name, !empty($_POST['year']) ? $_POST['year'] : '');
         } catch (MasterException $e) {
             //var_dump($e->getMessage(), $e->getStorageName()); exit;
             $moderator_storages = $master->getModeratorStorages();
             if (!empty($moderator_storages[$e->getStorageName()])) {
 public function indexPost()
 {
     var_dump($_POST['gor']);
     $ERRORS = array("NO_ERROR" => "0x000 - Ошибок нет.", "ERR_ONLY_ONE_ORDER" => "0x001 - Разрешена только одна заявка в запросе.", "ERR_INCORRECT_REQUEST" => "0x002 - Некорректный XML-файл или формат не распознан.", "ERR_ORDER_NOT_EXISTS" => "0x003 - Заявка с указанным номером не существует, или у Вас нет прав для совершения данной операции.", "ERR_INCORRECT_P-C_LINK" => "0x004 - Проверьте связь панелей с контейнерами. Имеются ошибки.", "ERR_ACCESS_DENIED" => "0x005 - Недостаточно прав для совершения данной операции.", "ERR_DEMOGRAPHY" => "0x006 - Неверно заполнена демография пациента. Обязательные поля - фамилия, пол, дата рождения.", "ERR_ORDERNO_REGERROR" => "0x007 - Заявка с указанным номером уже существует.", "ERR_ORDER_IS_REGISTERED" => "0x008 - Заявка уже зарегистрирована или у Вас нет прав для совершения данной операции.", "ERR_NO_DATES" => "0x009 - Неверено указаны или отсутствуют даты для интервала поиска направлений.", "ERR_JSON_GENERATING" => "0x010 - Внутренняя ошибка генерации запроса.");
     //require_once("../../../../ecodes.php");
     date_default_timezone_set('Europe/Moscow');
     $demo_clients = array("3434", "2222", "0361");
     $testclient = false;
     $port = 1028;
     if (in_array(@\Session::get("clientcode"), $demo_clients)) {
         $f = new FuncControllers();
         $testclient = true;
         $port = 1029;
     } else {
         $f = new FuncControllers();
     }
     $post = "";
     foreach ($_POST as $key => $val) {
         $post .= "key: " . $key . ", val:" . $val . "; ";
     }
     $get = "";
     foreach ($_GET as $key => $val) {
         $get .= "key: " . $key . ", val:" . $val . "; ";
     }
     $ips = array('82.149.201.102', '46.226.98.218', '46.226.99.146', '196.254.140.244');
     $alert_email = "*****@*****.**";
     $clients_info = array('1831' => array('host' => '82.144.95.131', 'login' => 'nakff', 'password' => 'H7sc6yT', 'inboxdir' => 'inbox', 'outboxdir' => 'outbox'), '2062' => array('host' => '82.144.95.131', 'login' => 'nakff', 'password' => 'H7sc6yT', 'inboxdir' => 'inbox', 'outboxdir' => 'outbox'), '2055' => array('host' => '82.144.95.131', 'login' => 'nakff', 'password' => 'H7sc6yT', 'inboxdir' => 'inbox', 'outboxdir' => 'outbox'));
     if (!(\Session::get('userCheck') == 0)) {
         $clientid = \Session::get('clientid');
         $valid_user = \Session::get('username');
     } else {
         $response = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
         $response .= "<response status=\"failed\">\n";
         $response .= "\t<comments>Ошибка авторизации</comments>\n";
         $response .= "</response>";
         //$f->writeEventToFile("=== ".date("d.m.Y H:i:s")." Ошибка авторизации ===\nIP: ".implode(',',$f->getIP())."\n===\n\n");
         $event = "=== " . date("d.m.Y H:i:s") . " Ошибка авторизации ===\nIP: " . implode(",", $f->getIP()) . "\nлогин/пароль\nPOST data: " . implode(", ", $_POST) . "\nGET data:" . implode(", ", $_GET) . "\n===\n\n";
         if (in_array($f->getIP(true), $ips)) {
             mail($alert_email, "Report from NACPP.API", $event);
             $f->writeEventToFile($event, "eventsALEXEY.log");
         } else {
             $f->writeEventToFile($event, "plugins/events.log");
         }
         die($response);
     }
     if (\Input::has("act")) {
         $act = \Input::get('act');
     }
     if (\Input::has('catalog')) {
         $catalog = \Input::get("catalog");
     }
     //$xml_post = @file_get_contents('php://input');
     var_dump($_POST);
     // $xml = $_POST['as'];
     $event = "=== " . date("d.m.Y H:i:s") . " Тех. информация ===\nКлиент (id): " . $clientid . "\nIP: " . implode(",", $f->getIP()) . "\nPOST data: " . $post . "\nGET data:" . $get . "\nXML (raw): " . $xml_post . "\nXML (parsed): " . $xml . "\n===\n\n";
     $f->writeEventToFile($event, "/home/limsadmin/site/plugins/events.log");
     if (in_array($f->getIP(true), $ips)) {
         mail($alert_email, "Report from NACPP.API", $event);
         $f->writeEventToFile($event, "eventsALEXEY.log");
     }
     switch ($act) {
         case "push-ftp":
             if (!isset($clients_info[$clientid])) {
                 die("No FTP auth information");
             }
             $user = $clients_info[$clientid]['login'];
             $pass = $clients_info[$clientid]['password'];
             $host = $clients_info[$clientid]['host'];
             $dir = $clients_info[$clientid]['inboxdir'];
             $query = "select first 10 f.folderno from folders f where f.clientid = " . $clientid . " and f.logdate > current_date - 31 and f.apprsts not in ('D','R') and exists(select o.id from orders ord\n\t\t\t\tinner join ordtask o on ord.id = o.ordersid\n\t\t\t  \twhere ord.folderno = f.folderno and ord.apprsts not in ('D','R') and o.apprsts = 'T' and o.remote = 'N' )  order by f.folderno";
             $stmt = $this->DBquery->query3($query);
             foreach ($stmt as $row) {
                 $row = (array) $row;
                 $folderno = $row['FOLDERNO'];
                 $file = "ftp://{$user}:{$pass}@{$host}/" . $dir . "/" . $folderno . '.xml';
                 $params = array('domain' => 'https://192.168.0.17:' . $port . '/api/integration/result.xml', 'cookies' => 'cookies.txt', 'params' => array('api-key' => '5b2e6d61-1bea-4c8f-811e-b95a946a7e46', 'orderno' => $folderno, 'fupdate' => 'Y', 'client-id' => $clientid));
                 $data = getJsonMainList($params);
                 $stream_options = array('ftp' => array('overwrite' => true));
                 $stream_context = stream_context_create($stream_options);
                 $f = fopen($file, 'w', false, $stream_context);
                 fwrite($f, $data);
                 fclose($f);
                 //$cid = ftp_connect("ftp://$user:$pass@$host/".$dir."/");
                 //$res = ftp_login($cid, $user, $pass);
             }
             break;
         case "get-ftp":
             break;
         case "report":
             //print version of results...
             if (\Input::has('id')) {
                 $folderno = $f->foldernoFixCheck(htmlspecialchars(\Input::get("id")));
                 if (!isOwner($folderno, $clientid)) {
                     $response = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
                     $response .= "<response status=\"failed\">\n";
                     $response .= "\t<comments>Ошибка! Вы не имеете прав, для просмотра данной заявки (Код ошибки: " . $ERRORS["ERR_ACCESS_DENIED"] . ")</comments>\n";
                     $response .= "</response>";
                     echo $response;
                     die;
                 }
                 $guid = $f->GUID();
                 header('Content-Disposition: filename=' . $guid);
                 header('Content-Type: application/pdf');
                 $params = array('domain' => 'https://192.168.0.17:' . $port . '/api/report.json', 'cookies' => 'cookies.txt', 'params' => array('api-key' => '5b2e6d61-1bea-4c8f-811e-b95a946a7e46', 'folderno' => $folderno, 'client-id' => $clientid), 'client-id' => $clientid);
                 if (isset($_GET["logo"]) || isset($_POST["logo"])) {
                     $params['params']['logo'] = "1";
                 }
                 $json = getJsonMainList($params);
                 $obj = json_decode($json, true);
                 echo base64_decode($obj["data"][0]["pdf"]);
             }
             break;
         case "request-status":
             $req = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
             $req .= "<request>\n";
             check_input($xml_post, $ips, $clientid, $alert_email);
             $orders = array();
             $count = 0;
             foreach ($xml->xpath('//request') as $request) {
                 foreach ($request->order as $o) {
                     foreach ($o->attributes() as $x => $y) {
                         $res = ib_query("SELECT APPRSTS FROM FOLDERS WHERE FOLDERNO = '" . foldernoFixCheck($y) . "'");
                         $row = ibase_fetch_row($res);
                         $req .= "<order orderno=\"" . $y . "\" status=\"" . $row[0] . "\">\n";
                     }
                     $count++;
                 }
             }
             $req .= "</request>\n";
             echo $req;
             break;
         case "free-orders":
             if (isset($_GET["n"])) {
                 $n = $_GET["n"];
             } else {
                 die('Отсутствует запрос.');
             }
             $query = "SELECT FOLDERNO FROM GET_FREE_FOLDERS(" . $clientid . "," . $n . ")";
             $stmt = ib_query($query);
             $response = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
             $response .= "<pool>\n";
             while ($row = ibase_fetch_row($stmt)) {
                 $response .= "<orderno>" . $row[0] . "</orderno>\n";
             }
             $response .= "</pool>";
             echo $response;
             break;
         case "pending":
             $clientcodes = "";
             $netsql = "select coalesce(c2.id, c1.id) from clients c1 left join clients c2 on c1.netid = c2.netid where c1.id = '" . $clientid . "' ";
             $stmt = ib_query($netsql);
             while ($row = ibase_fetch_row($stmt)) {
                 $clientcodes .= $row[0] . ",";
             }
             $clientcodes .= "-1";
             $query = "select f.folderno from folders f where f.clientid in (" . $clientcodes . ") and f.logdate > current_date - 31 and f.apprsts not in ('D','R') and exists(select o.id from orders ord inner join ordtask o on ord.id = o.ordersid  where ord.folderno = f.folderno and ord.apprsts not in ('D','R') and o.apprsts = 'T' and o.remote = 'N' ) order by f.folderno";
             $stmt = ib_query($query);
             $response = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
             $response .= "<pending>\n";
             while ($row = ibase_fetch_row($stmt)) {
                 $response .= "<orderno>" . $row[0] . "</orderno>\n";
             }
             $response .= "</pending>";
             echo $response;
             break;
         case "request-delete":
             check_input($xml_post, $ips, $clientid, $alert_email);
             $orders = array();
             $count = 0;
             foreach ($xml->xpath('//request') as $request) {
                 $folderno = "";
                 foreach ($request->order as $o) {
                     foreach ($o->attributes() as $x => $y) {
                         if ($x == "orderno") {
                             $folderno = $y;
                         }
                     }
                 }
                 if ($folderno == "") {
                     $folderno = $request->orderno;
                 }
                 $folderno = foldernoFixCheck($folderno);
                 if (isFolderReg($folderno) || !isOwner($folderno, $clientid)) {
                     $response = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
                     $response .= "<response status=\"failed\">\n";
                     $response .= "\t<comments>Ошибка! Заявка редактированию не подлежит. (Код ошибки: " . $ERRORS["ERR_ORDER_IS_REGISTERED"] . ")</comments>\n";
                     $response .= "</response>";
                     echo $response;
                     die;
                 }
             }
             $query = "SELECT xml FROM INT_REJECT_FOLDER ('" . foldernoFixCheck($folderno) . "','" . $valid_user . "','" . $clientid . "')";
             $stmt = ib_query($query);
             while ($row = ibase_fetch_row($stmt)) {
                 echo $row[0];
             }
             break;
         case "request-orders":
             check_input($xml_post, $ips, $clientid, $alert_email);
             $dt1 = "";
             $dt2 = "";
             foreach ($xml->xpath('//request') as $request) {
                 $d = strtotime($request->date_start);
                 if ($d == FALSE) {
                     $response = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
                     $response .= "<response status=\"failed\">\n";
                     $response .= "\t<comments>Ошибка! Неверно указан интервал дат для поиска направлений. (Код ошибки: " . $ERRORS["ERR_NO_DATES"] . ")</comments>\n";
                     $response .= "</response>";
                     echo $response;
                     die;
                 }
                 $dt1 = date('Y/m/d', $d);
                 $d = strtotime($request->date_end);
                 if ($d == FALSE) {
                     $response = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
                     $response .= "<response status=\"failed\">\n";
                     $response .= "\t<comments>Ошибка! Неверно указан интервал дат для поиска направлений. (Код ошибки: " . $ERRORS["ERR_NO_DATES"] . ")</comments>\n";
                     $response .= "</response>";
                     echo $response;
                     die;
                 }
                 $dt2 = date('Y/m/d', $d);
                 $params = array('domain' => 'https://192.168.0.17:' . $port . '/api/integration/folders.xml', 'cookies' => 'cookies.txt', 'params' => array('api-key' => '5b2e6d61-1bea-4c8f-811e-b95a946a7e46', 'start-date' => $dt1, 'end-date' => $dt2, 'client-id' => $clientid), 'client-id' => $clientid);
                 $data = getJsonMainList($params);
                 echo $data;
                 die;
             }
             $response = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
             $response .= "<response status=\"failed\">\n";
             $response .= "\t<comments>Ошибка! Проверьте правильность XML-файла.</comments>\n";
             $response .= "</response>";
             echo $response;
             die;
             break;
         case "request-result":
             if (isset($_GET["orderno"]) && is_numeric($_GET["orderno"])) {
                 if (!isOwner(foldernoFixCheck($_GET["orderno"]), $clientid)) {
                     $response = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
                     $response .= "<response status=\"failed\">\n";
                     $response .= "\t<comments>Ошибка! Вы не имеете прав, для просмотра данной заявки (Код ошибки: " . $ERRORS["ERR_ACCESS_DENIED"] . ")</comments>\n";
                     $response .= "</response>";
                     echo $response;
                     die;
                 }
                 $params = array('domain' => 'https://192.168.0.17:' . $port . '/api/integration/result.xml', 'cookies' => 'cookies.txt', 'params' => array('api-key' => '5b2e6d61-1bea-4c8f-811e-b95a946a7e46', 'orderno' => foldernoFixCheck($_GET["orderno"]), 'fupdate' => 'Y'), 'client-id' => $clientid);
                 $data = getJsonMainList($params);
                 echo $data;
             } else {
                 check_input($xml_post, $ips, $clientid, $alert_email);
                 $orders = array();
                 $count = 0;
                 foreach ($xml->xpath('//request') as $request) {
                     $folderno = "";
                     foreach ($request->order as $o) {
                         foreach ($o->attributes() as $x => $y) {
                             if ($x == "orderno") {
                                 $folderno = $y;
                             }
                         }
                     }
                     if ($folderno == "") {
                         $folderno = $request->orderno;
                     }
                     $folderno = foldernoFixCheck($folderno);
                 }
                 if (!isOwner(foldernoFixCheck($folderno), $clientid)) {
                     $response = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
                     $response .= "<response status=\"failed\">\n";
                     $response .= "\t<comments>Ошибка! Вы не имеете прав, для просмотра данной заявки (Код ошибки: " . $ERRORS["ERR_ACCESS_DENIED"] . ")</comments>\n";
                     $response .= "</response>";
                     echo $response;
                     die;
                 } else {
                     $params = array('domain' => 'https://192.168.0.17:' . $port . '/api/integration/result.xml', 'cookies' => 'cookies.txt', 'params' => array('api-key' => '5b2e6d61-1bea-4c8f-811e-b95a946a7e46', 'orderno' => foldernoFixCheck($folderno), 'fupdate' => 'Y'), 'client-id' => $clientid);
                     $data = getJsonMainList($params);
                     echo $data;
                 }
             }
             break;
             //-----------------------------------------------------
         //-----------------------------------------------------
         case "request-edit":
             check_input($xml_post, $ips, $clientid, $alert_email);
             $container = array();
             $panels = array();
             foreach ($xml->xpath('//request') as $request) {
                 $folderno = foldernoFixCheck($request->orderno);
                 if (isFolderReg($folderno)) {
                     $response = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
                     $response .= "<response status=\"failed\">\n";
                     $response .= "\t<comments>Ошибка! Заявка редактированию не подлежит. (Код ошибки: " . $ERRORS["ERR_ORDER_IS_REGISTERED"] . ")</comments>\n";
                     $response .= "</response>";
                     echo $response;
                     die;
                 }
                 $guid = $request->personal->guid;
                 $name = $request->personal->name;
                 $surname = $request->personal->surname;
                 $patronimic = $request->personal->patronimic;
                 $birthdate = $request->personal->birthdate;
                 $gender = $request->personal->gender;
                 $clientcode = $request->personal->clientcode;
                 $cardno = $request->personal->cardno;
                 $datecollect = $request->personal->datecollect;
                 $department = $request->personal->department;
                 $doctor = $request->personal->doctor;
                 $diagnosis = $request->personal->diagnosis;
                 $comment = $request->personal->comment;
                 $pregnancy = $request->personal->pregnancy;
                 $phase = $request->personal->phase;
                 $insurer = $request->personal->insurer;
                 $passno = $request->personal->passno;
                 $passseries = $request->personal->passseries;
                 $address = $request->personal->address;
                 $phone = $request->personal->phone;
                 $email = $request->personal->email;
                 $policy = $request->personal->policy;
                 $cito = $request->personal->cito;
                 $diuresis = $request->personal->diuresis;
                 $weight = $request->personal->weight;
                 $height = $request->personal->height;
                 $antibiotics = $request->personal->antibiotics;
                 $antibstart = $request->personal->antibstart;
                 $antibend = $request->personal->antibend;
                 $antib = !empty($antibend) && !empty($antibstart);
                 foreach ($request->containers->container as $c) {
                     $id = $c->attributes()->id;
                     foreach ($c->attributes() as $x => $y) {
                         $container["{$id}"]["{$x}"] = $y;
                     }
                 }
                 foreach ($request->panels->panel as $p) {
                     $code = $p->attributes()->code;
                     foreach ($p->attributes() as $x => $y) {
                         $panel["{$code}"]["{$x}"] = $y;
                     }
                 }
             }
             if (!isOwner(foldernoFixCheck($folderno), $clientid)) {
                 $response = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
                 $response .= "<response status=\"failed\">\n";
                 $response .= "\t<comments>Ошибка! Вы не имеете прав, для просмотра данной заявки (Код ошибки: " . $ERRORS["ERR_ACCESS_DENIED"] . ")</comments>\n";
                 //$response .= "\t<comments2>".$folderno." ".$clientid."</comments2>\n";
                 $response .= "</response>";
                 echo $response;
                 die;
             }
             if (!checkPanelsAndContainers($panel, $container)) {
                 $response = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
                 $response .= "<response status=\"failed\">\n";
                 $response .= "\t<comments>Ошибка! Некорректный XML-файл (Код ошибки: " . $ERRORS["ERR_INCORRECT_P-C_LINK"] . ")</comments>\n";
                 $response .= "</response>";
                 echo $response;
                 die;
             }
             foreach ($panel as $p) {
                 $code = $p["code"];
                 $panel["{$code}"]["diagnosis"] = isDiagnosis($folderno, $code) == false ? 0 : 1;
             }
             //				GLASS = '"."',
             //				TUBE = '"."',
             //				LOGUSER = '******',
             //				LOGDATE = '".date("d.m.Y")."',
             $q = "";
             if ($datecollect) {
                 $q .= !empty($q) ? "," : "";
                 $q .= "DATE_COLLECTED = '" . $datecollect . "'";
             }
             if ($name) {
                 $q .= !empty($q) ? "," : "";
                 $q .= "NAME = '" . $name . "'";
             }
             if ($surname) {
                 $q .= !empty($q) ? "," : "";
                 $q .= "SURNAME = '" . $surname . "'";
             }
             if ($patronimic) {
                 $q .= !empty($q) ? "," : "";
                 $q .= "PATRONIMIC = '" . $patronimic . "'";
             }
             if ($insurer) {
                 $q .= !empty($q) ? "," : "";
                 $q .= "INSURER = '" . $insurer . "'";
             }
             if ($cardno) {
                 $q .= !empty($q) ? "," : "";
                 $q .= "CARD = '" . $cardno . "'";
             }
             if ($phone) {
                 $q .= !empty($q) ? "," : "";
                 $q .= "PHONE = '" . $phone . "'";
             }
             if ($email) {
                 $q .= !empty($q) ? "," : "";
                 $q .= "EMAIL = '" . $email . "'";
             }
             if ($weight) {
                 $q .= !empty($q) ? "," : "";
                 $q .= "WEIGHT = '" . $weight . "'";
             }
             if ($height) {
                 $q .= !empty($q) ? "," : "";
                 $q .= "HEIGHT = '" . $height . "'";
             }
             if ($passseries) {
                 $q .= !empty($q) ? "," : "";
                 $q .= "PASSPORT_SERIES = '" . $passseries . "'";
             }
             if ($passno) {
                 $q .= !empty($q) ? "," : "";
                 $q .= "PASSPORT_NUMBER = '" . $passno . "'";
             }
             if ($gender) {
                 $q .= !empty($q) ? "," : "";
                 $q .= "GENDER = '" . $gender . "'";
             }
             if ($doctor) {
                 $q .= !empty($q) ? "," : "";
                 $q .= "DOCTOR = '" . $doctor . "'";
             }
             if ($diagnosis) {
                 $q .= !empty($q) ? "," : "";
                 $q .= "DIAGNOSIS = '" . $diagnosis . "'";
             }
             if ($comment) {
                 $q .= !empty($q) ? "," : "";
                 $q .= "COMMENTS = '" . $comment . "'";
             }
             if ($pregnancy) {
                 $q .= !empty($q) ? "," : "";
                 $q .= "PREGNANCY = '" . $pregnancy . "'";
             }
             if ($address) {
                 $q .= !empty($q) ? "," : "";
                 $q .= "ADDRESS = '" . $address . "'";
             }
             if ($policy) {
                 $q .= !empty($q) ? "," : "";
                 $q .= "POLICY = '" . $policy . "'";
             }
             if ($cito) {
                 $q .= !empty($q) ? "," : "";
                 $q .= "URGENT = '" . $cito . "'";
             }
             if ($diuresis) {
                 $q .= !empty($q) ? "," : "";
                 $q .= "DIURESIS = '" . $diuresis . "'";
             }
             if ($antibstart) {
                 $q .= !empty($q) ? "," : "";
                 $q .= "ANTIB_START = '" . $antibstart . "'";
             }
             if ($antibend) {
                 $q .= !empty($q) ? "," : "";
                 $q .= "ANTIB_END = '" . $antibend . "'";
             }
             if ($antibiotics) {
                 $q .= !empty($q) ? "," : "";
                 $q .= "ANTIBIOTICS = '" . $antibiotics . "'";
             }
             if ($antib) {
                 $q .= !empty($q) ? "," : "";
                 $q .= "ANTIB = '" . $antib . "'";
             }
             if ($department) {
                 $q .= !empty($q) ? "," : "";
                 $q .= "DEPARTMENT = '" . $department . "'";
             }
             $query = "UPDATE FOLDERS SET " . $q . " WHERE FOLDERNO = '" . $folderno . "'";
             $query = str_replace("''", "null", $query);
             $result = ib_query($query);
             foreach ($panel as $p) {
                 if ($p["action"] == "delete") {
                     $query = "execute procedure DEL_PANEL('" . $folderno . "','" . $p["code"] . "','" . $valid_user . "')";
                     $query = str_replace("''", "null", $query);
                     $result = ib_query($query);
                 } else {
                     if ($p["action"] == "add") {
                         if (isFolderReg($folderno)) {
                             $query = "execute procedure ADD_PANEL1('" . $folderno . "','" . $p["code"] . "','" . $valid_user . "')";
                         } else {
                             $query = "execute procedure ADD_PANEL('" . $folderno . "','" . $p["code"] . "','" . $valid_user . "')";
                         }
                         $query = str_replace("''", "null", $query);
                         $result = ib_query($query);
                     } else {
                         echo "err";
                     }
                 }
             }
             foreach ($container as $c) {
                 foreach ($panel as $p) {
                     //				echo "p cont: ".$p["container"]."; c id: ".$c["id"]."<br/>";
                     if (strcmp($p["container"], $c["id"]) == 0) {
                         $q = "";
                         //if ($c["containertype"]) $q .= " CONTAINERTYPEID = '".$c["containertype"]."'";
                         if ($c["external"]) {
                             $q .= " EXTERNALID = '" . $c["external"] . "'";
                         }
                         if ($c["biomaterial"] && $p["diagnosis"] == "1") {
                             $q .= ", MATTYPEID = '" . $c["biomaterial"] . "'";
                         }
                         //if ($c["glassno"]) $q .= ", GLASSNO = '".$c["glassno"]."'";
                         //if ($c["tubeno"]) $q .= ", TUBENO = '".$c["tubeno"]."'";
                         $query = "update foldercontainers set " . $q . " where id = (select first 1 distinct fc.id from foldercontainers fc\n\t\t\t\t\t  inner join orders ord on ord.folderno = fc.folderno\n\t\t\t\t\t  inner join ordtask o on o.ordersid = ord.id and fc.id = o.containerid\n\t\t\t\t\t  inner join panels p on p.id = ord.panelid\n\t\t\t\t\t  where fc.folderno = '" . $folderno . "' and p.code = '" . $p["code"] . "')";
                         $query = str_replace("''", "null", $query);
                         $result = ib_query($query);
                         break;
                         // ЕСЛИ БУДУТ ГЛЮКИ, ТО ЗАКОММЕНИТИТЬ BREAK
                     }
                 }
             }
             $response = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
             $response .= "<response status=\"ok\">\n";
             $response .= "\t<order orderno=\"" . $folderno . "\" action=\"register\" status=\"ok\" />\n";
             $response .= "</response>";
             echo $response;
             break;
         case "request-add":
             //echo "debug";n
             $f->check_input($xml_post, $ips, $clientid, $alert_email);
             $error = false;
             $container = array();
             $panels = array();
             //var_dump($xml_post);
             var_dump(base64_decode($xml));
             foreach ($xml->xpath('//request') as $request) {
                 //echo $debug;
                 if (isset($request->personal->orderno)) {
                     $orderno = $request->personal->orderno;
                 } else {
                     $orderno = false;
                 }
                 $guid = $request->personal->guid;
                 $name = mb_strtoupper($request->personal->name, 'UTF-8');
                 if (strlen($request->personal->surname) > 0) {
                     $surname = mb_strtoupper($request->personal->surname, 'UTF-8');
                 } else {
                     $error = true;
                 }
                 if (strlen($request->personal->birthdate) > 0 && dateCheck($request->personal->birthdate)) {
                     $birthdate = date("d.m.Y", strtotime($request->personal->birthdate));
                 } else {
                     $error = true;
                 }
                 if (strlen($request->personal->gender) > 0) {
                     $gender = $request->personal->gender;
                 } else {
                     $error = true;
                 }
                 $patronimic = mb_strtoupper($request->personal->patronimic, 'UTF-8');
                 $clientcode = $request->personal->clientcode;
                 //для сеток, здесь нужны хитрые проверки...
                 if ($clientcode * 1.0 > 0 || $clientcode == 'С') {
                     $cres = $f->DBquery->query("select id from clients where clientcode = '" . $clientcode . "'");
                     $crow = (array) $cres[0];
                     $clientid = $crow['ID'];
                 }
                 $cardno = $request->personal->cardno;
                 if (dateCheck($request->personal->datecollect, true)) {
                     $datecollect = $request->personal->datecollect;
                 } else {
                     $error = true;
                 }
                 $department = $request->personal->department;
                 $doctor = $request->personal->doctor;
                 $diagnosis = $request->personal->diagnosis;
                 $comment = $request->personal->comment;
                 $organisation = $request->personal->organisation;
                 if (isset($request->personal->pregnacy) && !empty($request->personal->pregnacy)) {
                     $pregnacy = $request->personal->pregnacy;
                 } else {
                     $pregnacy = 0;
                 }
                 $phase = $request->personal->phase;
                 $insurer = $request->personal->insurer;
                 $passno = $request->personal->passno;
                 $passseries = $request->personal->passseries;
                 $address = $request->personal->address;
                 $phone = $request->personal->phone;
                 $email = $request->personal->email;
                 $policy = $request->personal->policy;
                 $cito = $request->personal->cito;
                 $diuresis = $request->personal->diuresis;
                 $weight = $request->personal->weight;
                 $height = $request->personal->height;
                 $antibiotics = $request->personal->antibiotics;
                 $antibstart = $request->personal->antibstart;
                 $antibend = $request->personal->antibend;
                 $antib = $antibend && $antibstart ? "Y" : "N";
                 if (!empty($request->personal->aisorder)) {
                     $aisorder = $request->personal->aisorder;
                 } else {
                     if (!empty($orderno)) {
                         $aisorder = $orderno;
                     } else {
                         $aisorder = false;
                     }
                 }
                 if (!empty($request->personal->guid)) {
                     $guid = ", GUID = '" . $request->personal->guid . "'";
                 } else {
                     $guid = "";
                 }
                 $container = array();
                 foreach ($request->containers->container as $c) {
                     $id = $c->attributes()->id;
                     foreach ($c->attributes() as $x => $y) {
                         $container["{$id}"]["{$x}"] = $y;
                     }
                 }
                 foreach ($request->panels->panel as $p) {
                     $code = $p->attributes()->code;
                     foreach ($p->attributes() as $x => $y) {
                         $panel["{$code}"]["{$x}"] = $y;
                     }
                 }
             }
             $simple = false;
             //echo "count containers: ".count($container);
             //echo "debug";
             if (count($container) == 0) {
                 $simple = true;
             } else {
                 if (!checkPanelsAndContainers($panel, $container)) {
                     $response = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
                     $response .= "<response status=\"failed\">\n";
                     $response .= "\t<comments>Ошибка! Некорректный XML-файл (Код ошибки: " . $ERRORS["ERR_INCORRECT_P-C_LINK"] . ")</comments>\n";
                     $response .= "</response>";
                     echo $response;
                     die;
                 }
             }
             if ($error) {
                 $response = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
                 $response .= "<response status=\"failed\">\n";
                 $response .= "\t<comments>Ошибка! Некорректный XML-файл (Код ошибки: " . $ERRORS["ERR_DEMOGRAPHY"] . ")</comments>\n";
                 $response .= "</response>";
                 echo $response;
                 die;
             }
             $panels = "";
             foreach ($panel as $p) {
                 $panels .= $p["code"] . ",";
             }
             $panels = substr($panels, 0, -1);
             if ($orderno == false || $simple) {
                 $panels = transliterate($panels);
                 if ($orderno == false) {
                     $query = "select folderno from n_registration ('" . $surname . "','" . $name . "','" . $patronimic . "','" . $gender . "','" . $datecollect . "','" . $birthdate . "', null, '" . mb_convert_case($phase, MB_CASE_UPPER, "UTF-8") . "', " . $pregnacy . ", '" . $cito . "', " . $clientid . ",'" . $doctor . "','" . $policy . "','" . $insurer . "','" . $diuresis . "','" . $diagnosis . "','" . $antib . "','" . $antibiotics . "','" . $antibstart . "','" . $antibend . "','" . $address . "', null,'" . $panels . "','" . $comment . "');";
                 } else {
                     $query = "select folderno from n_registration_folderno ('" . $orderno . "','" . $surname . "','" . $name . "','" . $patronimic . "','" . $gender . "','" . $datecollect . "','" . $birthdate . "', null, '" . mb_convert_case($phase, MB_CASE_UPPER, "UTF-8") . "', " . $pregnacy . ", '" . $cito . "', " . $clientid . ",'" . $doctor . "','" . $policy . "','" . $insurer . "','" . $diuresis . "','" . $diagnosis . "','" . $antib . "','" . $antibiotics . "','" . $antibstart . "','" . $antibend . "','" . $address . "', null,'" . $panels . "','" . $comment . "');";
                 }
                 //echo $query;
                 $query = str_replace("''", "null", $query);
                 $result = ib_query($query);
                 $row = ibase_fetch_row($result);
                 $folderno = $row[0];
             } else {
                 $panels = "";
                 foreach ($container as $c) {
                     $panels .= $c["external"] . ":";
                     foreach ($panel as $p) {
                         if ($p["container"] * 1 == $c["id"] * 1) {
                             $panels .= $p["code"] . ",";
                         }
                     }
                     $panels = substr($panels, 0, -1) . ";";
                 }
                 $panels = transliterate($panels);
                 $query = "select status from n_registration_cont ('" . $orderno . "','" . $surname . "','" . $name . "','" . $patronimic . "','" . $gender . "','" . $datecollect . "','" . $birthdate . "', null, '" . mb_convert_case($phase, MB_CASE_UPPER, "UTF-8") . "', " . $pregnacy . ", '" . $cito . "', " . $clientid . ",'" . $doctor . "','" . $policy . "','" . $insurer . "','" . $diuresis . "','" . $diagnosis . "','" . $antib . "','" . $antibiotics . "','" . $antibstart . "','" . $antibend . "','" . $address . "', null,'" . $panels . "','" . $comment . "');";
                 $query = str_replace("''", "null", $query);
                 $result = ib_query($query);
                 $row = ibase_fetch_row($result);
                 if ($row[0] !== "OK") {
                     $response = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
                     //$response .= $query ."\n";
                     $response .= "<response status=\"failed\">\n";
                     $response .= "\t<comments>Ошибка! Невозможно зарегистрировать направление под номером '" . $orderno . "' (Код ошибки: " . $ERRORS["ERR_ORDERNO_REGERROR"] . ")</comments>\n";
                     $response .= "</response>";
                     echo $response;
                     die;
                 }
                 $folderno = $orderno;
             }
             $event = "=== " . date("d.m.Y H:i:s") . " REGISTRATION INFO ===\nIP: " . implode(",", getIP()) . "\nQUERY: " . $query . "\n\n";
             $event .= "Server response: " . $row[0] . "\n";
             foreach ($panel as $p) {
                 $code = $p["code"];
                 $panel["{$code}"]["diagnosis"] = isDiagnosis($folderno, $code) == false ? 0 : 1;
             }
             if ($aisorder) {
                 $query = "UPDATE FOLDERS SET ORGANISATION = '" . mb_substr($organisation, 0, 50, "UTF-8") . "', INSURER = '" . $insurer . "', LOGUSER = '******', LOGDATE = '" . date("d.m.Y") . "', CARD = '" . $cardno . "', GLASS = '" . "', TUBE = '" . "', PHONE = '" . $phone . "', EMAIL = '" . $email . "', WEIGHT = '" . $weight . "', HEIGHT = '" . $height . "', PASSPORT_SERIES = '" . $passseries . "', PASSPORT_NUMBER = '" . $passno . "', DEPARTMENT = '" . $department . "', AISORDER = '" . $aisorder . "'" . $guid . " WHERE FOLDERNO = '" . $folderno . "'";
             } else {
                 $query = "UPDATE FOLDERS SET ORGANISATION = '" . mb_substr($organisation, 0, 50, "UTF-8") . "', INSURER = '" . $insurer . "', LOGUSER = '******', LOGDATE = '" . date("d.m.Y") . "', CARD = '" . $cardno . "', GLASS = '" . "', TUBE = '" . "', PHONE = '" . $phone . "', EMAIL = '" . $email . "', WEIGHT = '" . $weight . "', HEIGHT = '" . $height . "', PASSPORT_SERIES = '" . $passseries . "', PASSPORT_NUMBER = '" . $passno . "', DEPARTMENT = '" . $department . "'" . $guid . " WHERE FOLDERNO = '" . $folderno . "'";
             }
             $query = str_replace("''", "null", $query);
             $result = ib_query($query);
             $event .= " UPDATE: " . $query . "\n\n";
             writeEventToFile($event, "events-query.log");
             if (!$simple) {
                 foreach ($container as $c) {
                     foreach ($panel as $p) {
                         if ($p["container"] * 1 == $c["id"] * 1) {
                             $q = "";
                             //if ($c["containertype"]) $q .= " fcl.CONTAINERTYPEID = '".$c["containertype"]."'";
                             if ($c["external"]) {
                                 $q .= " fcl.EXTERNALID = '" . $c["external"] . "'";
                             }
                             if ($c["biomaterial"] && $p["diagnosis"] == "1") {
                                 $q .= ", fcl.MATTYPEID = '" . $c["biomaterial"] . "'";
                             }
                             //if ($c["glassno"]) $q .= ", fcl.GLASSNO = '".$c["glassno"]."'";
                             //if ($c["tubeno"]) $q .= ", fcl.TUBENO = '".$c["tubeno"]."'";
                             $query = "update foldercontainers fcl set " . $q . " where fcl.folderno = '" . $folderno . "' and exists(select distinct fc.*, p.code from foldercontainers fc\n\t\t\t\t\t\t  inner join orders ord on ord.folderno = fc.folderno\n\t\t\t\t\t\t  inner join ordtask o on o.ordersid = ord.id and fc.id = o.containerid\n\t\t\t\t\t\t  inner join panels p on p.id = ord.panelid\n\t\t\t\t\t\t  where fc.folderno = '" . $folderno . "' and p.code = '" . $p["code"] . "' and fcl.id = o.containerid)";
                             $query = str_replace("''", "null", $query);
                             $result = ib_query($query);
                             break;
                         }
                     }
                 }
             }
             $response = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
             $response .= "<response status=\"ok\">\n";
             $response .= "\t<order orderno=\"" . $folderno . "\" action=\"register\" status=\"ok\" />\n";
             $response .= "</response>";
             echo $response;
             break;
         case "get-catalog":
             switch ($catalog) {
                 case "containertypes":
                     $query = "select id, containertype, color from CONTAINERTYPES order by id ASC";
                     $stmt = $f->DBquery->query($query);
                     $xml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n";
                     $xml .= "<containertypes>\n";
                     foreach ($stmt as $row) {
                         $row = (array) $row;
                         $xml .= "<containertype code=\"" . $row['ID'] . "\" color=\"" . trim($row['COLOR']) . "\">" . $row['CONTAINERTYPE'] . "</containertype>\n";
                     }
                     $xml .= "</containertypes>";
                     echo $xml;
                     break;
                 case "contgroups":
                     $query = "select id,contgroup from CONTGROUPS order by id ASC";
                     $stmt = ib_query($query);
                     $xml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n";
                     $xml .= "<contgroups>\n";
                     while ($row = ibase_fetch_row($stmt)) {
                         $xml .= "<contgroup code=\"" . $row[0] . "\">" . $row[1] . "</contgroup>\n";
                     }
                     $xml .= "</contgroups>";
                     echo $xml;
                     break;
                     //-----------------------------------
                 //-----------------------------------
                 case "bio":
                     $query = "select id, mattype from MATTYPES order by id ASC";
                     $stmt = $f->DBquery->query($query);
                     $xml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n";
                     $xml .= "<biomaterials>\n";
                     foreach ($stmt as $row) {
                         $row = (array) $row;
                         $xml .= "<biomaterial code=\"" . $row['ID'] . "\">" . $row['MATTYPE'] . "</biomaterial>\n";
                     }
                     $xml .= "</biomaterials>";
                     echo $xml;
                     break;
                 case "panels":
                     $query = "select id, code, panel from PANELS WHERE status = 'A' order by id ASC";
                     $stmt = $f->DBquery->query($query);
                     $xml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n";
                     $xml .= "<panels>\n";
                     foreach ($stmt as $row) {
                         $row = (array) $row;
                         $xml .= "<panel code=\"" . $row['CODE'] . "\">\n";
                         $xml .= "<name>" . $row['PANEL'] . "</name>";
                         $xml .= "<containers>";
                         $query1 = "select p.mattype_id, p.containertype_id, p.containerno, p.id from panel_containers p WHERE p.panel_id = " . $row['ID'];
                         $stmt1 = $f->DBquery->query($query1);
                         foreach ($stmt1 as $row1) {
                             $row1 = (array) $row1;
                             $xml .= "<container biomaterial=\"" . $row1['MATTYPE_ID'] . "\" containertype=\"" . $row1['CONTAINERTYPE_ID'] . "\" containerno=\"" . $row1['CONTAINERNO'] . "\" code=\"" . $row1['ID'] . "\">";
                             $query2 = "select test_id from panel_tests where container_id = " . $row1['ID'];
                             $stmt2 = $f->DBquery->query($query2);
                             foreach ($stmt2 as $row2) {
                                 $row2 = (array) $row2;
                                 $xml .= "<test code=\"" . $row2['TEST_ID'] . "\" />";
                             }
                             $xml .= "</container>";
                         }
                         $xml .= "</containers>";
                         $xml .= "</panel>";
                     }
                     $xml .= "</panels>";
                     echo $xml;
                     break;
                 case "pricelists":
                     $query = "select p.id, cast(p.datebegin as date), cast(p.dateend as date), p.status, p.defaults from pricelists p where p.clientid = " . $clientid . " order by id ";
                     $stmt = ib_query($query);
                     $xml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n";
                     $xml .= "<pricelists>\n";
                     while ($row = ibase_fetch_row($stmt)) {
                         $xml .= "<pricelist>\n<code>" . $row[0] . "</code>\n<datebegin>" . $row[1] . "</datebegin>\n<dateend";
                         if ($row[2]) {
                             $xml .= ">" . $row[2] . "</dateend>\n";
                         } else {
                             $xml .= " />\n";
                         }
                         $xml .= "<status>" . $row[3] . "</status>\n";
                         $xml .= "<defaults>" . $row[4] . "</defaults>\n</pricelist>\n";
                     }
                     $xml .= "</pricelists>";
                     echo $xml;
                     break;
                 case "prices":
                     $query = "select p.code, pr.cost from\n    panels p inner join prices pr on pr.panelid = p.id\n             inner join pricelists r on r.id = pr.pricelistid\nwhere r.id =  " . $_GET["pricelist"] . " and r.clientid = " . $clientid;
                     $stmt = ib_query($query);
                     $xml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n";
                     $xml .= "<prices>\n";
                     while ($row = ibase_fetch_row($stmt)) {
                         $xml .= "<panel><code>" . $row[0] . "\n<price>" . $row[1] . "</price>\n</panel>\n";
                     }
                     $xml .= "</prices>";
                     echo $xml;
                     break;
                     //для диллеров - отображение только тех панелей, которые есть в прайсах.
                 //для диллеров - отображение только тех панелей, которые есть в прайсах.
                 case "panels2":
                     $query = "select distinct p.id, p.code, p.panel from\n    panels p inner join prices pr on pr.panelid = p.id inner join pricelists pc on pc.id = pr.pricelistid where pc.clientid = " . $clientid . " order by p.code ";
                     $stmt = ib_query($query);
                     $xml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n";
                     $xml .= "<panels>\n";
                     while ($row = ibase_fetch_row($stmt)) {
                         $xml .= "<panel code=\"" . $row[1] . "\">\n";
                         $xml .= "<name>" . $row[2] . "</name>";
                         $xml .= "<containers>";
                         $query1 = "select m.id, t.test_id from panel_containers p\n\t\t\t\t\t\t   inner join mattypes m on m.id = p.mattype_id\n\t\t\t\t\t\t   inner join panel_tests t on t.container_id = p.id WHERE p.panel_id = " . $row[0] . " order by m.id ASC";
                         $stmt1 = ib_query($query1);
                         while ($row1 = ibase_fetch_row($stmt1)) {
                             $xml .= "<container material=\"" . $row1[0] . "\">";
                             $xml .= "<test id=\"" . $row1[1] . "\" />";
                             $xml .= "</container>";
                         }
                         $xml .= "</containers>";
                         $xml .= "</panel>";
                     }
                     $xml .= "</panels>";
                     echo $xml;
                     break;
                 case "tests2":
                     $query = "select t.id, t.testname from\n    panels p inner join panel_containers pc on pc.panel_id = p.id\n             inner join panel_tests pt on pt.container_id = pc.id\n             inner join tests t on t.id = pt.test_id\n             inner join prices pr on pr.panelid = p.id\n             inner join pricelists r on r.id = pr.pricelistid\nwhere r.clientid = " . $clientid . " order by t.id ";
                     $stmt = ib_query($query);
                     $xml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n";
                     $xml .= "<tests>";
                     while ($row = ibase_fetch_row($stmt)) {
                         $xml .= "<test code=\"" . $row[0] . "\">";
                         $xml .= "<name>" . $row[1] . "</name>\n";
                         $xml .= "<analytes>\n";
                         $query1 = "select a.id, a.analyte, a.analtype, a.iso, u.unit, a.sorter from analytes a\n\t\t\t\t\t\t   inner join units u on u.id = a.units WHERE a.testcode = " . $row[0] . " ORDER BY a.id";
                         $stmt1 = ib_query($query1);
                         while ($row1 = ibase_fetch_row($stmt1)) {
                             $xml .= "<analyte code=\"" . $row1[0] . "\">\n";
                             $xml .= "<name>" . $row1[1] . "</name>\n";
                             $analtype = $row1[2];
                             if ($analtype == 3) {
                                 $analtype = 'N';
                             } else {
                                 $analtype = 'C';
                             }
                             $xml .= "<type>" . $analtype . "</type>\n";
                             $xml .= "<iso>" . $row1[3] . "</iso>\n";
                             $xml .= "<units>" . $row1[4] . "</units>\n";
                             $xml .= "<sorter>" . $row1[5] . "</sorter>\n";
                             $xml .= "</analyte>\n";
                         }
                         $xml .= "</analytes>\n";
                         $xml .= "</test>";
                     }
                     $xml .= "</tests>";
                     echo $xml;
                     break;
                 case "tests":
                     $query = "select t.id, t.testname from tests t ORDER BY t.id";
                     $stmt = $f->DBquery->query($query);
                     $xml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n";
                     $xml .= "<tests>";
                     foreach ($stmt as $row) {
                         $row = (array) $row;
                         $xml .= "<test code=\"" . $row['ID'] . "\">";
                         $xml .= "<name>" . $row['TESTNAME'] . "</name>\n";
                         $xml .= "<analytes>\n";
                         $query1 = "select a.id, a.analyte, a.analtype, a.iso, u.unit, a.sorter from analytes a inner join units u on u.id = a.units WHERE a.testcode = " . $row['ID'] . " ORDER BY a.id";
                         $stmt1 = $f->DBquery->query($query1);
                         foreach ($stmt1 as $row1) {
                             $row1 = (array) $row1;
                             $xml .= "<analyte code=\"" . $row1['ID'] . "\">\n";
                             $xml .= "<name>" . $row1['ANALYTE'] . "</name>\n";
                             $analtype = $row1['ANALTYPE'];
                             if ($analtype == 3) {
                                 $analtype = 'N';
                             } else {
                                 $analtype = 'C';
                             }
                             $xml .= "<type>" . $analtype . "</type>\n";
                             $xml .= "<iso>" . $row1['ISO'] . "</iso>\n";
                             $xml .= "<units>" . $row1['UNIT'] . "</units>\n";
                             $xml .= "<sorter>" . $row1['SORTER'] . "</sorter>\n";
                             $xml .= "</analyte>\n";
                         }
                         $xml .= "</analytes>\n";
                         $xml .= "</test>";
                     }
                     $xml .= "</tests>";
                     echo $xml;
                     break;
             }
             break;
         default:
             $event = "=== " . date("d.m.Y H:i:s") . " Остустствует запрос. Ошибка входных данных. ===\nIP: " . implode(',', getIP()) . "\nКлиент (id): " . $clientid . "\n===\n\n";
             writeEventToFile($event);
             if (in_array(getIP(true), $ips)) {
                 mail($alert_email, "Report from NACPP.API", $event);
                 writeEventToFile($event, "eventsALEXEY.log");
             }
             echo "Отсутствует запрос.";
     }
 }