/** * устанавливает root_id для дерева разделов * * @param текущий раздел $id * @param предок $pid */ function setRootID($id, $pid) { //$id = get('id','0','p'); $root_id = sql_getValue("SELECT root_id FROM tree WHERE id = " . $id); $err = sql_getErrNo(); // проверка на существования поля в таблице( если нет : 1054) if ((!$root_id || $root_id == '0') && !$err) { // определяем $root_id // если root_id нашли у предыдущего $home_id = sql_getValue("SELECT root_id FROM tree WHERE id = " . $pid['pid']); if ($home_id) { sql_query("UPDATE tree SET root_id = " . $home_id . " WHERE id=" . $id); } else { $pid = $pid['pid']; do { $home = sql_getRow("SELECT pid,root_id FROM tree WHERE id = " . $pid); // если все таки не нашли то останавливаемся , когда добежали до корня if ($pid == $home['pid']) { $home['root_id'] = $pid; break; } $pid = $home['pid']; } while (empty($home['root_id'])); sql_query("UPDATE tree SET root_id = " . $home['root_id'] . " WHERE id=" . $id); } } }
function table_get_flat(&$value, &$column, &$row) { if (!$value) { $row = sql_getRow('SELECT * FROM objects WHERE id=' . $row['object_id']); } else { $row = sql_getRow('SELECT * FROM obj_elem_free WHERE id=' . $value); } if (!$row) { return ''; } $ret = ''; if ($row['room']) { $ret .= $row['room'] . '-комн., '; } if ($row['total_area'] > 0) { $ret .= $row['total_area'] . '/'; } if ($row['living_area'] > 0) { $ret .= $row['living_area'] . '/'; } if ($row['kitchen_area'] > 0) { $ret .= $row['kitchen_area'] . '/'; } if ($row['storey']) { $ret .= ', ' . $row['storey'] . ' этаж'; } return $ret; }
function ElemInit() { global $cfg, $sections, $hidden_sections, $_stat, $_sites, $intlang; $row = array(); $modules_in_row = array(); $i = 0; $id = (int) get('id'); if ($id) { $row = sql_getRow("SELECT * FROM `admin_groups` WHERE id='" . $id . "'"); $row['rights'] = unserialize($row['rights']); } // ALLOW -> DEL INS UPD SELECT // none -> 0 0 0 0 = 0 // view -> 0 0 0 1 = 1 // edit -> 0 1 1 1 = 7 // del -> 1 1 1 1 = 15 $row['radios'] = array('0' => '', '1' => '', '7' => '', '15' => ''); // если указаны скрытые модули - надо их также вывести // для возможности задания прав группам пользователей. if (isset($hidden_sections)) { $sections = array_merge($sections, $hidden_sections); } foreach ($sections as $key => $section) { $row['menu'][$i]['title'] = utf($section[langId()]); $row['menu'][$i]['i'] = $i; foreach ($section['modules'] as $module_key => $module) { if (count(explode("/", $module_key)) > 1) { $arr = explode("/", $module_key); $module = $arr[0]; } if (!is_module_auth($module_key)) { continue; } // set the title unset($title); $title = $module[langID()]; if (!isset($title)) { switch ($module) { case 'stat': $title = $_stat[$module_key][langID()]; break; case 'sites': $title = $_sites[$module_key][langID()]; break; } } if (!in_array($module . '_' . $title, $modules_in_row)) { $row['menu'][$i]['rows'][] = array('menu' => $i, 'name' => 'fld[rights][' . $module_key . ']', 'title' => utf($title), 'selected' => !empty($row['rights'][$module_key]) ? $row['rights'][$module_key] : 0); $modules_in_row[] = $module . '_' . $title; } } $i++; } foreach ($this->elem_str as $str_key => $str_val) { $row['str_' . $str_key] = $str_val[$intlang]; } $table = $this->Parse($row, 'admin_groups.editform.tmpl'); $this->elem_fields['columns']['table'] = array('type' => 'words', 'value' => $table); return parent::ElemInit(); }
function ElemInit() { $columns = sql_getRows("SHOW COLUMNS FROM " . $this->elem_table . "", true); if (!isset($columns['footer_text_radio'])) { sql_query("ALTER TABLE " . $this->elem_table . " ADD footer_text_radio TINYINT( 1 ) UNSIGNED NOT NULL DEFAULT '0' COMMENT '0 - редактор текста; 1 - html-код баннера'"); } if (!isset($columns['footer_title'])) { sql_query("ALTER TABLE {$this->elem_table} ADD footer_title VARCHAR( 255 ) NOT NULL COMMENT 'Название кнопки Подробнее';"); } if (!isset($columns['footer_title_link'])) { sql_query("ALTER TABLE {$this->elem_table} ADD footer_title_link VARCHAR( 255 ) NOT NULL COMMENT 'Ссылка на кнопке Подробнее';"); } $id = (int) get('id'); if ($id) { $infoblock_end = sql_getRow("SELECT * FROM " . $this->elem_table . " WHERE id = " . $id); if ($infoblock_end['footer_text_radio']) { $this->elem_fields['columns']['footer_text']['value'] = htmlspecialchars($infoblock_end['footer_text']); $this->elem_fields['columns']['footer_text_area']['value'] = $infoblock_end['footer_text']; } else { $this->elem_fields['columns']['footer_text_fck']['value'] = $infoblock_end['footer_text']; } } $this->script .= "\n\n function elem1(name) {\n return \$('#tr_fld\\\\[" . $this->tabname . "\\\\]\\\\[' + name + '\\\\]');\n }\n\n function elemName1(name) {\n return 'fld[" . $this->tabname . "][' + name + ']';\n };\n\n function getFck1(name) {\n name = elemName1(name);\n for(nameFck in CKEDITOR.instances) {\n if(name == nameFck) {\n return CKEDITOR.instances[name];\n }\n }\n }\n\n function open_fck_footer(name_fck, name_area) {\n var fck = getFck1(name_fck);\n var footer_text_fck = \$(elem1(name_fck));\n var footer_text_area = \$(elem1(name_area));\n\n footer_text_fck.children('span').show();\n footer_text_area.hide();\n\n var data = footer_text_area.children('textarea').val();\n if (data.length) fck.setData(data);\n\n fck.container.show();\n fck.updateElement();\n }\n\n function close_fck_footer(name_fck, name_area) {\n var fck = getFck1(name_fck);\n var footer_text_fck = \$(elem1(name_fck));\n var footer_text_area = \$(elem1(name_area));\n fck.container.hide();\n fck.updateElement();\n\n footer_text_fck.children('span').hide();\n footer_text_area.show();\n footer_text_area.children('textarea').css({\n 'width' : '98%',\n 'height' : fck.config.height\n });\n\n var data = fck.getData();\n if (data.length) footer_text_area.children('textarea').val(data);\n }\n\n \$(function () {\n var footer_text_radio = \$(elem1('footer_text_radio')).children('input');\n \$(footer_text_radio).click(function() {\n if(\$(this).val() == 1) {\n close_fck_footer('footer_text_fck', 'footer_text_area');\n } else {\n open_fck_footer('footer_text_fck', 'footer_text_area');\n }\n });\n\n CKEDITOR.on( 'instanceReady', function( ev )\n {\n " . (isset($infoblock_end) && $infoblock_end['footer_text_radio'] ? "close_fck_footer" : "open_fck_footer") . "('footer_text_fck', 'footer_text_area');\n });\n });\n "; TElems::ElemInit(); }
function verify_event(&$event, $user_id) { // проверка разрешенных видов нотификации //----------------------------------------------- // получаем идентификатор события $event = sql_getRow("SELECT id, recipient FROM notify_events WHERE name='" . $event . "'"); // получаем доступные плугины для события $plugins = sql_getRows("SELECT plugin FROM notify_compare WHERE event=" . $event['id'], true); // проверка событие для клиента или для админа. if ($event['recipient'] == 'client') { //получаем идентификатор группы пользователя $group_id = sql_getValue("SELECT group_id FROM auth_users_groups WHERE user_id=" . $user_id); //получаем, разрешенные плугины для группы $group_plugins = sql_getRows("SELECT nt.name FROM notify_groups AS ng\n\t\t\t\t\t\t\t\t\t\t\tLEFT JOIN notify_types AS nt ON nt.id=ng.notif_id\n\t\t\t\t\t\t\t\t\t\t\tWHERE ng.group_id=" . $group_id, true); if (!sql_getErrNo()) { $plugins = array_intersect($plugins, $group_plugins); } /* //получаем виды нотификации, выбранные пользователем $user_plugins = sql_getRows(" SELECT nt.name FROM notify_user AS nu LEFT JOIN notify_types AS nt ON nu.notify_id=nt.id WHERE nu.user_id=".$user_id." AND nu.event_id=".$event['id'] , true); if (!sql_getErrNo()){ $plugins = array_intersect($plugins,$user_plugins); } */ } return $plugins; }
/** * Отправка уведомления для события * @param string $event_name - кодовое название события * @param string $emails - на какие адреса отправлять (через запятую); если пусто, возьмутся из настроек события * @param array $data - данные для передачи в шаблон * @param string $attach - прикладываемый файл * @return bool */ function Send($event_name, $emails = '', $data = array(), $attach = '') { $event = sql_getRow("SELECT * FROM {$this->_table_events} WHERE event='" . mysql_real_escape_string($event_name) . "'"); if (!$event) { return $this->setError("В таблице {$this->_table_events} нет события {$event_name}"); } if (!$emails) { $emails = $event['mails']; } if (!$emails) { return $this->setError("Пустой список адресов для отправки"); } /** * @var TRusoft_View $view */ $view =& Registry::get('TRusoft_View'); // Парсинг темы и текста письма $text = $this->parse($event['template'], $data); if (!$text) { return $this->setError("Пустой текст письма"); } $subject = $this->parse($event['subject'], $data); if (!$subject) { return $this->setError("Пустая тема письма"); } // Отправка $res = $this->sendNotify($emails, $subject, $text, $event['replyto'], $attach); if ($res !== true) { return $this->setError("Ошибка отправки сообщения: " . $res); } $this->addToSent($event_name, $emails, $subject, $text, $attach); return true; }
function showType() { global $notify_subscribe; $data['type'] = get('type', '', 'pg'); $res = mysql_query($notify_subscribe[$data['type']]); for ($i = 0; $i < mysql_num_fields($res); $i++) { $field = mysql_fetch_field($res); $comment = sql_getValue("\n\t\t\t\t\tSELECT \n\t\t\t\t\tcomment\n\t\t\t\t\tFROM phpmyadmin.pma_column_info \n\t\t\t\t\tWHERE \n\t\t\t\t\ttable_name='" . $field->table . "'\n\t\t\t\t\tAND column_name='" . $field->name . "'\n\t\t\t\t\tAND db_name='" . MYSQL_DB . "' \n\t\t\t\t\t"); $data['fields'][$field->table . '.' . $field->name] = $comment; } $data['fld'] = sql_getRow('SELECT * FROM notify_subscribe_tpls WHERE id="' . $data['type'] . '"'); include_fckeditor(); $oFCKeditor =& Registry::get('FCKeditor'); $oFCKeditor->ToolbarSet = 'Small'; $oFCKeditor->Value = $data['fld']['header']; $data['fld']['header'] = $oFCKeditor->ReturnFCKeditor('fld[header]', '100%', '100px'); $oFCKeditor =& Registry::get('FCKeditor'); $oFCKeditor->ToolbarSet = 'Source'; $oFCKeditor->Value = $data['fld']['template']; $data['fld']['template'] = $oFCKeditor->ReturnFCKeditor('fld[template]', '100%', '200px'); $oFCKeditor =& Registry::get('FCKeditor'); $oFCKeditor->ToolbarSet = 'Small'; $oFCKeditor->Value = $data['fld']['footer']; $data['fld']['footer'] = $oFCKeditor->ReturnFCKeditor('fld[footer]', '100%', '100px'); $this->AddStrings($data); $tpl = NOTIFY_DIR . 'tmpls/' . $this->name . '.editform.tmpl'; if (is_file($tpl)) { return Parse($data, $tpl); } return $content; }
/** * функци¤ возвращет конкретное значение из полученного массива данных по ip * * @param string - ключ массива. ≈сли интересует конкретное значение. * люч может быть равным 'inetnum', 'country', 'city', 'region', 'district', 'lat', 'lng' * @param boolean - устанавливаем хранить данные в базе или нет * ≈сли true, то в таблицу ipgeobase будут записаны данные по ip и повторные запросы на ipgeobase происходить не будут. * ≈сли false, то данные посто¤нно будут запрашиватьс¤ с ipgeobase * * @return array OR string - дополнительно читайте комментарии внутри функции. */ function get_value($key = false, $from_db = true) { $key_array = array('inetnum', 'country', 'city', 'region', 'district', 'lat', 'lng'); if (!in_array($key, $key_array)) { $key = false; } $data = null; // если используем базу, то достаем данные if ($from_db) { $numeric_ip = $this->numeric_ip($this->ip); $data = sql_getRow("SELECT * FROM `{$this->dbname}`.`{$this->table}` WHERE (from_ip>={$numeric_ip} AND to_ip<={$numeric_ip}) LIMIT 1"); } if (!$data) { $data = $this->get_geobase_data(); $inetnum = explode('-', $data['inetnum']); if ($data && $data['country']) { sql_insert("`{$this->dbname}`.`{$this->table}`", array('from_ip' => $this->numeric_ip($inetnum[0]), 'to_ip' => $this->numeric_ip($inetnum[1]), 'country' => $data['country'], 'city' => $data['city'], 'region' => $data['region'], 'district' => $data['district'], 'lat' => $data['lat'], 'lng' => $data['lng'])); } } if ($key) { return $data[$key]; // если указан ключ, возвращаем строку с нужными данными } else { return $data; // иначе возвращаем массив со всеми данными } }
/** * Инициализация * @param bool $reset - принудательно обновить данные о пользователе */ function init($reset = false) { static $_user_data = array(); if (!isset($_user_data[$this->_id]) || $reset) { $_user_data[$this->_id] = sql_getRow("SELECT * FROM {$this->_table} WHERE id={$this->_id} LIMIT 1"); } $this->_data = $_user_data[$this->_id]; }
function getClientDetails($id) { $client = sql_getRow("SELECT id, CONCAT(name,' ',lname) AS fullname FROM " . $this->table . " WHERE reg_date!=0 AND id=" . $id); if (!is_array($client)) { return ''; } $details = array(array('name' => $this->str('client_id'), 'value' => $client['id']), array('name' => $this->str('fullname'), 'value' => $client['fullname'])); return $details; }
function getClientDetails($id) { $client = sql_getRow("SELECT id, fio AS fullname, balance FROM " . $this->table . " WHERE id=" . $id); if (!is_array($client)) { return ''; } $details = array(array('name' => $this->str('client_id'), 'value' => $client['id']), array('name' => $this->str('fullname'), 'value' => $client['fullname'])); return $details; }
/** * Вызывается перед сохранением в базу * * @param array $fld * @return array */ function ElemRedactBefore($fld) { $fld = parent::ElemRedactBefore($fld); $error = ""; $page_id = get('id', 0, 'gp'); $page_pid = get('pid', 0, 'gp'); if ($page_pid) { $parent = sql_getRow("SELECT dir, pids, level FROM " . $this->elem_table . " WHERE id=" . $page_pid); } else { $page_pid = sql_getValue("SELECT pid FROM `" . $this->elem_table . "` WHERE id=" . $page_id); $parent = sql_getRow("SELECT dir, pids, level FROM " . $this->elem_table . " WHERE id=" . $page_pid); } if (!$page_id) { // создание нового раздела $auto = sql_getRow("SHOW TABLE STATUS LIKE '" . $this->elem_table . "'"); if ($auto['Auto_increment']) { $new_id = $auto['Auto_increment']; } if ($page_pid == $page_id) { $fld['level'] = 1; } else { $fld['level'] = $parent['level'] + 1; } $fld['priority'] = sql_getValue("SELECT MAX(priority) FROM `" . $this->elem_table . "` WHERE pid=" . $page_pid) + 1; } $page = $page_id ? $page_id : $new_id; if ($page_pid != $page_id) { # pids $pids = explode('/', $parent['pids']); if (!$pids[0]) { array_shift($pids); } if (!$pids[count($pids) - 1]) { array_pop($pids); } $pids[] = $page_pid; $fld['pids'] = '/' . join('/', $pids) . '/'; # dir $fld['dir'] = $parent['dir'] . $page . '/'; } else { # pids $fld['pids'] = '/' . $page_pid . '/'; $fld['dir'] = '/' . $page . '/'; } # изменим next у родителя sql_query("UPDATE tree SET next='1' WHERE id='" . (isset($parent['id']) ? $parent['id'] : $page_pid) . "'"); # Проверка на существование dir $check = sql_getValue("SELECT id FROM " . $this->elem_table . " WHERE dir='" . $fld['dir'] . "'"); if ($check && $check != $page_id) { $error_tab = $k; $error = "Раздел с таким URL уже существует"; } return array('fld' => $fld, '_error_text' => $error); }
function GetStats() { $sess = sql_getRow("SHOW TABLE STATUS LIKE '" . STAT_SESSIONS_TABLE . "'", 'number'); $log = sql_getRow("SHOW TABLE STATUS LIKE '" . STAT_LOG_TABLE . "'", 'number'); $pages = sql_getRow("SHOW TABLE STATUS LIKE '" . STAT_PAGES_TABLE . "'", 'number'); $agents = sql_getRow("SHOW TABLE STATUS LIKE '" . STAT_AGENTS_TABLE . "'", 'number'); $db['Data_length'] = $sess['Data_length'] + $log['Data_length'] + $pages['Data_length'] + $agents['Data_length']; $db['Index_length'] = $sess['Index_length'] + $log['Index_length'] + $pages['Index_length'] + $agents['Index_length']; $db['Rows'] = $sess['Rows'] + $log['Rows'] + $pages['Rows'] + $agents['Rows']; return array('STATINFO' => $this->str('info'), 'rows' => array(0 => array('key' => $this->str('info_size'), 'val' => number_format(($db['Data_length'] + $db['Index_length']) / 1024, 2, ',', ' ') . " KB"), 1 => array('key' => $this->str('info_rows'), 'val' => $db['Rows']))); }
function table_get_ban($val, $row) { // Узнаем забаннен этот посетитель или нет $res = sql_getRow("SELECT id, ban FROM auth_users WHERE id='" . $row['client_id'] . "'"); if (!$res['ban']) { // Можно забаннить return "<input type='image' src='/admin/images/icons/icon.rcard.gif' width='16' height='18' style='cursor: hand' title='" . $this->str('ban1') . "' onclick='if (confirm(\"" . sprintf($this->str('confirm1'), $row['login']) . "\") == true) location.href=\"cnt.php?page=stat/stat_banlist&do=editinsertips&id=" . $row['client_id'] . "\"; return false;'>"; } else { // Можно разбаннить return "<input type='image' src='/admin/images/icons/icon.gcard.gif' width='16' height='18' style='cursor: hand' title='" . $this->str('ban2') . "' onclick='if (confirm(\"" . sprintf($this->str('confirm2'), $row['login']) . "\") == true) location.href=\"cnt.php?page=stat/stat_banlist&do=editdeleteips&id=" . $row['client_id'] . "\"; return false;'>"; } }
/** * Вызывается после сохранения в БД * @param array() $fld * @param integer $id * @return array() */ function ElemRedactAfter($fld, $id) { $tree = sql_getValue("SELECT * FROM tree WHERE root_id='" . $fld['root_id'] . "' AND id=pid LIMIT 1"); if (!$tree) { // сделать в дереве раздел (только один раздел с type=home) $tree_row = sql_getRow("SELECT * FROM tree WHERE id=pid LIMIT 1"); if ($tree_row) { $tree_row['id'] = $tree_row['pid'] = $tree_row['root_id'] = $fld['root_id']; $tree_row['pids'] = '/' . $fld['root_id'] . '/'; $tree_row['next'] = 0; $tree_row['priority'] = (int) sql_getValue("SELECT MAX(priority) FROM tree WHERE id=pid") + 1; sql_insert('tree', $tree_row); } } return $fld; }
function EditParamForm() { $id = (int) get('id', ''); if ($id) { $row = sql_getRow("SELECT * FROM product_type_params WHERE id={$id}"); } else { $row['product_type_id'] = (int) get('product_type_id'); } // pr($row['table']); $this->AddStrings($row); // $row['thisname'] = 'product_types_param'; $GLOBALS['title'] = $this->str('title_edit_param'); $row['id'] = $id; $row = $this->Parse($row, 'product_type_param.editform.tmpl'); return $row; }
function GetText() { # выдача скрипта, который возвращает значение из модального окна $instance = get('instance', '', 'p'); $ptable = get('ptable', '', 'p'); $pfields = get('pfields', '', 'p'); $pid = (int) get('pid', 0, 'p'); $uptime = get('uptime', 0, 'p'); $hash = get('hash', 0, 'p'); # поля, которые нужны.. $pfields = explode(", ", $pfields); foreach ($pfields as $field) { $name = explode("fld[", $field); $name = explode("]", $name[1]); $fields[] = $name[0]; } # выбираем текущее значение $row = sql_getRow('SELECT * FROM ' . $ptable . ' WHERE id=' . $pid); # выбираем все изменения $changes = sql_getRows('SELECT gzip FROM ' . $this->table . ' WHERE ptable="' . $ptable . '" AND pid=' . $pid . ' AND uptime >= ' . $uptime . ' ORDER BY uptime DESC'); # начинаем изменять текущие значения проходя по массивам... foreach ($changes as $value) { $a = unserialize(gzuncompress($value)); $row = array_merge($row, $a); } $keys = array(); $values = array(); foreach ($row as $key => $value) { if (!in_array($key, $fields)) { unset($row[$key]); } else { $keys[] = "'" . $key . "'"; $values[] = "'" . $value . "'"; } } # $row - массив значений, которые были на заданную дату $script = '<script type="text/javascript">' . "\n"; $script .= "function data() {\n"; $script .= " this.key = new Array(" . implode(",", $keys) . ");\n"; $script .= " this.value = new Array(" . implode(",", $values) . ");\n"; $script .= "}\n"; $script .= "data = new data();"; $script .= 'window.returnValue = data;' . "\n"; $script .= 'window.close();'; $script .= '</script>'; return $script; }
function getCurrency() { $valute = get('valute', 'RUR', 'pgs'); session_start(); if (!isset($_SESSION['currency']) || !isset($_SESSION['valute']) || $_SESSION['valute'] != $valute) { $_SESSION['valute'] = $valute; $currency = sql_getRow("SELECT value, display, name FROM currencies WHERE name = '" . $valute . "'"); if (!empty($currency)) { $_SESSION['currency'] = $currency; } else { unset($_SESSION['currency']); } } else { $currency = $_SESSION['currency']; } session_write_close(); return $currency; }
function ElemInit() { $id = (int) get('id', 0, 'pg'); if ($id && ($row = sql_getRow("SELECT * FROM " . $this->elem_table . " WHERE id = " . (int) $id))) { $this->elem_fields['columns']['text']['value'] = "<h1>Текст:</h1><div class='tabContent'>" . $row['text'] . "</div>"; $files = unserialize($row['attach']); if (!empty($files)) { $attach = "\n <h1>Файлы:</h1>\n <div class='tabContent'>\n <table class='ajax_table_main' style='width: 100%'>\n <tr>\n <th>Путь</td>\n <th>Размер (байт)</td>\n </tr>"; foreach ($files as $file) { $file['name'] = '/' . ltrim($file['name'], '/'); $attach .= "\n <tr>\n <td><a href='{$file['name']}'>{$file['name']}</a></td>\n <td>{$file['size']}</td>\n </tr>\n "; } $attach .= "</table></div>"; $this->elem_fields['columns']['attach']['value'] = $attach; } } return parent::ElemInit(); }
function Login() { global $user, $intlangs; session_start(); session_write_close(); $login = mysql_real_escape_string(get('login', '', 'p')); $pwd = get('pwd', '', 'p'); $uri = get('uri', '', 'p'); $win = get('win', '', 'p'); $intlang = get('intlang', 0, 'p'); $token = get('token', '', 's'); # берем из сессии $aes_key = defined("AESKEY") ? AESKEY : $this->aes_key; if (!$login) { $login = '******'; } @(include_once 'keygen.phpe'); $row = sql_getRow("SELECT u.*, g.rights, g.deny_ids, AES_DECRYPT(u.pwd, '{$aes_key}') AS passw FROM " . $this->table . " as u LEFT JOIN admin_groups as g ON g.id<=>u.group_id WHERE login='******'"); $passwd = strlen($row['pwd']) == 32 ? $row['pwd'] : $row['passw']; if (isset($passwd) && (md5($passwd . $token) === $pwd || function_exists('keygen') && strcmp($pwd, md5(md5(keygen()) . $token)) == 0)) { unset($row['pwd']); unset($row['passw']); if ($row['rights']) { $row['rights'] = unserialize($row['rights']); } $user = $row; session_start(); $_SESSION['user'] =& $user; setcookie('intlang', $intlang, time() + 3600 * 24 * 31); $_SESSION['intlang'] =& $intlang; // Разрешим доступ к файловому менеджеру $_SESSION['KCFINDER'] = array(); $_SESSION['KCFINDER']['disabled'] = false; session_write_close(); //записывапем данные в log_access sql_query("INSERT INTO log_access(`login`,`ip`,`date`) VALUES('" . htmlspecialchars($user['login']) . "','" . $_SERVER["REMOTE_ADDR"] . "','" . date('YmdHis') . "')"); if ($win) { return "<script>window.parent.location.reload()</script>"; } HeaderExit($uri); } return $this->Show($this->str('e_pwd')); }
function Show() { $this->Init(); $this->AddStrings($data); // Вспомогательные данные $this->today = mktime(0, 0, 0, date('m'), date('d'), date('Y')); $diff = time() - sql_getValue("SELECT MIN(time) FROM " . STAT_SESSIONS_TABLE); $this->all_monthes = 12 * (date('Y', $diff) - 1970) + date('n', $diff); // Количество посетителей (%s - нужно чтобы туда вставить выборку по времени) $stat[] = $this->GetSummaryRow('<a href="?page=stat/stat_attendance&period=0&disp_by=hour">' . $this->str('visitors') . '</a>', "SELECT COUNT(*) FROM " . $this->sess_table . " WHERE %s robot='0'"); // Количество зарегистированных клиентов на сайте /* if(STAT_CLIENT_REPORT) $stat[] = $this->GetSummaryRow( '<a href="?page=stat/stat_clients&period=0">'.$this->str('reg_clients').'</a>', "SELECT COUNT(*) FROM ".$this->sess_table." WHERE %s robot='0' AND client_id!=0" );*/ if (STAT_CLIENT_REPORT) { $stat[] = $this->GetRobotsRow('<a href="?page=stat/stat_clients&period=0">' . $this->str('reg_clients') . '</a>', "SELECT CONCAT(COUNT(*), ' (', COUNT(DISTINCT(client_id)), ')') FROM " . $this->sess_table . " WHERE %s robot='0' AND client_id!=0"); } // Количество просмотренных страниц $stat[] = $this->GetSummaryRow('<a href="?page=stat/stat_popular&period=0">' . $this->str('pages') . '</a>', "SELECT SUM(loads) FROM " . $this->sess_table . " WHERE %s robot='0'"); // Количество новых посетителей $stat[] = $this->GetSummaryRow('<a href="?page=stat/stat_attendance&period=0&disp_by=hour">' . $this->str('new_visitors') . '</a>', "SELECT COUNT(*) FROM " . $this->sess_table . " WHERE %s robot='0' AND new_visitor='1'"); // Количество ip-адресов $stat[] = $this->GetSummaryRow('<a href="?page=stat/stat_ip&period=0">' . $this->str('ips') . '</a>', "SELECT COUNT(DISTINCT(ip)) FROM " . $this->sess_table . " WHERE %s robot='0'"); // Количество ошибочных страниц $stat[] = $this->GetSummaryRow('<a href="?page=stat/stat_errors&period=0">' . $this->str('errors') . '</a>', "SELECT COUNT(*) FROM " . $this->log_table . " WHERE %s status IN (404, 403)"); // Количество проиндексированных страниц с них $stat[] = $this->GetRobotsRow('<a href="?page=stat/stat_robots&period=0">' . $this->str('robots') . '</a>', "SELECT CONCAT(COUNT(DISTINCT(agent_id)), ' (', COUNT(*), ')') FROM " . $this->sess_table . " WHERE %s robot='1'"); // Main Table $data['table'] = $this->stat_table(array('columns' => array(array('header' => 'attendance', 'nowrap' => 1, 'valign' => 'top'), array('header' => 'today', 'align' => 'right', 'width' => '15%'), array('header' => 'yesterday', 'align' => 'right', 'width' => '15%'), array('header' => 'week', 'align' => 'right', 'width' => '15%'), array('header' => 'month', 'align' => 'right', 'width' => '15%')), 'data' => $stat)); // Stat Info Table $sess = sql_getRow("SHOW TABLE STATUS LIKE '" . STAT_SESSIONS_TABLE . "'", 'number'); $log = sql_getRow("SHOW TABLE STATUS LIKE '" . STAT_LOG_TABLE . "'", 'number'); $pages = sql_getRow("SHOW TABLE STATUS LIKE '" . STAT_PAGES_TABLE . "'", 'number'); $agents = sql_getRow("SHOW TABLE STATUS LIKE '" . STAT_AGENTS_TABLE . "'", 'number'); $db['Data_length'] = $sess['Data_length'] + $log['Data_length'] + $pages['Data_length'] + $agents['Data_length']; $db['Index_length'] = $sess['Index_length'] + $log['Index_length'] + $pages['Index_length'] + $agents['Index_length']; $db['Rows'] = $sess['Rows'] + $log['Rows'] + $pages['Rows'] + $agents['Rows']; $data['info'] = array('STATINFO' => $this->str('info'), 'rows' => array(0 => array('key' => $this->str('info_begin'), 'val' => $sess['Create_time']), 1 => array('key' => $this->str('info_last'), 'val' => $log['Update_time']), 2 => array('key' => $this->str('info_size'), 'val' => number_format(($db['Data_length'] + $db['Index_length']) / 1024, 2, ',', ' ') . " KB"), 3 => array('key' => $this->str('info_rows'), 'val' => $db['Rows']))); $data['site_select'] = $this->selectSite(array('hidden' => array('show' => $this->show))); return Parse($data, 'stat/stat.tmpl'); }
function ShowHelp() { $module = get('module', '', 'g'); $url = "http://help.rusoft.ru/getmanual.php?engine=3.6&module=" . $module . "&site=" . $_SERVER['HTTP_HOST']; $html = file_get_contents($url); if (!strpos($html, 'Документация по вашему запросу не найдена')) { // проверка наличия документации на русофте ob_end_clean(); ob_end_clean(); Header('Content-Length: 0'); Header('Location: ' . $url); } $row = sql_getRow("SELECT * FROM " . $this->table . " WHERE module='" . mysql_real_escape_string($module) . "'"); if (empty($row)) { die('Документация по этому модулю отсутствует'); } $this->AddStrings($row); return $this->Parse($row, $this->name . '.showhelp.tmpl'); }
function EditForm() { $id = (int) get('id', ''); $product_type_id = (int) get('product_type_id', ''); if (!$product_type_id && !$id) { return; } if ($id) { $row = sql_getRow("SELECT * FROM product_type_params WHERE id={$id}"); } else { $row['product_type_id'] = (int) get('product_type_id'); } $row['visible_checked'] = isset($row['visible']) ? 'checked' : (!$id ? 'checked' : ''); $this->AddStrings($row); $GLOBALS['title'] = $this->str('title_edit_param'); $row['id'] = $id; $row = $this->Parse($row, $this->name . '.editform.tmpl'); return $row; }
function ElemForm() { $id = (int) get('id', 0); if ($id) { $row = $this->getObject(); } if ($row['object']['obj_type_id'] == 'newbuild') { $row['object']['price'] = $row['object']['price_rub_print'] . '<br>' . $row['object']['price_dollar_print']; } else { $row['object']['price'] = number_format(doubleval(str_replace(',', '.', $row['object']['price_rub'])), 0, ',', ' ') . ' руб. (' . number_format(doubleval(str_replace(',', '.', $row['object']['price_dollar'])), 0, ',', ' ') . 'у.е. )'; } $row['object']['x'] = $row['object']['y'] = '0.000000'; if ($row['object']['address_id']) { $coordinats = sql_getRow('SELECT x, y FROM `obj_address` WHERE id=' . $row['object']['address_id']); $row['object']['x'] = $coordinats['x']; $row['object']['y'] = $coordinats['y']; } // добавляет в шаблон дефолтные строковые константы $this->AddStrings($row); return Parse($row, 'objects/elem_google.tmpl'); }
/** * Вернуть массив с результатами в срезе по конкретному вопросу * * @param int $quest_id * @return array|bool */ function getMoreResults(int $quest_id) { if (!$this->survey_id or !$quest_id) { return false; } $data = array(); $data['view'] = $this->result_view; $data['question'] = sql_getRow("SELECT * FROM " . $this->table_quests . " WHERE id = " . $quest_id); $data['questions'] = sql_getRows("SELECT id, text, type FROM " . $this->table_quests . " WHERE id <> " . $quest_id . " && id_survey = " . $this->survey_id . " ORDER BY priority", true); $query = in_array($data['question']['type'], array('single', 'multi')) ? "SELECT * FROM " . $this->table_variants . " WHERE id_quest = " . $quest_id : "SELECT *, text as id FROM " . $this->table_log . " WHERE id_quest = " . $quest_id . " GROUP BY text ORDER BY text"; $data['rows'] = sql_getRows($query); foreach ($data['rows'] as $key => $row) { $res = sql_getRows($query = "SELECT IF(l2.id_variant IS NOT NULL, l2.id_variant, l2.text) AS id_variant, l2.id_quest, COUNT(IF(l2.id_variant IS NOT NULL, l2.id_variant, l2.text)) cnt\n FROM " . $this->table_log . " as l1\n LEFT JOIN " . $this->table_log . " as l2 ON(l2.id_user = l1.id_user)\n WHERE IF(l1.id_variant IS NOT NULL, l1.id_variant, l1.text) = '" . $row['id'] . "' AND l2.id_quest<>" . $quest_id . " GROUP BY IF(l2.id_variant IS NOT NULL, l2.id_variant, l2.text)"); $re = array(); $total = array(); foreach ($res as $r) { $re[$r['id_variant']] = $r['cnt']; $total[$r['id_quest']] += $r['cnt']; } foreach ($data['questions'] as $qid => $quest) { $query = in_array($quest['type'], array('single', 'multi')) ? "SELECT * FROM " . $this->table_variants . " WHERE id_quest = " . $quest['id'] : "SELECT *, text AS id FROM " . $this->table_log . " WHERE id_quest = " . $quest['id'] . " GROUP BY text ORDER BY text"; $data['rows'][$key]['questions'][$qid]['vars'] = sql_getRows($query); $data['rows'][$key]['questions'][$qid]['text'] = $quest['text']; foreach ($data['rows'][$key]['questions'][$qid]['vars'] as $k => $variant) { $_id = in_array($quest['type'], array('single', 'multi')) ? $variant['id'] : $variant['id_variant']; $data['rows'][$key]['questions'][$qid]['vars'][$k]['cnt'] = $re[$_id]; $data['rows'][$key]['questions'][$qid]['vars'][$k]['percent'] = isset($total[$qid]) && isset($re[$_id]) ? round(100 * $re[$_id] / $total[$qid]) : 0; } } } $data['qid'] = $quest_id; return $data; }
function CopyTree($src, $trg, $top = true) { static $counter = array(); static $next_id = 0; // запишем что мы уже перенесли (для отмены рекурсии) $counter[] = $trg; // Если в данный элемент уже копировали, отменяем (для отмены рекурсии) if (in_array($src, $counter)) { return; } # Берем source $src_row = sql_getRow("SELECT * FROM " . $this->table . " WHERE id='" . $src . "'"); if (!$next_id) { $status = sql_getRow("SHOW TABLE STATUS LIKE '" . $this->table . "'"); $next_id = $status['Auto_increment']; } else { $next_id++; } # Обрабатываем unset($src_row['id']); $src_row['pid'] = $trg; # Вставляем $src_row['dir'] = 'tmp_' . count($counter); $trg = sql_insert($this->table, $src_row); # Ищем дочерние ветви и запускаем заново эту функцию $rows = sql_query("SELECT id FROM " . $this->table . " WHERE pid=" . $src); if ($rows) { while ($row = mysql_fetch_row($rows)) { $this->CopyTree($row[0], $trg, false); } } }
/** * Редактирование объявления */ function edit() { $page =& Registry::get('TPage'); $id = 0; $real_path = $_SERVER['REQUEST_URI']; if (substr($real_path, -1) != '/') { $real_path .= '/'; } $query = explode('?', $real_path); $pids = explode('/', $query[0]); $pos = array_search('edit', $pids); if ($pos !== false) { $id = (int) $pids[$pos + 1]; } if (!$id) { $page->tpl->assign(array('errors' => array('Объявление не указано!'))); $ret['errors_box'] = $page->tpl->fetch('errors_box.html'); $page->tpl->clear_assign('errors_box'); return $ret; } $auth =& Registry::get('TUserAuth'); $userid = (int) $auth->getCurrentUserId(); if (!$userid) { $page->tpl->assign(array('errors' => array('Вы не авторизованы!'))); $ret['errors_box'] = $page->tpl->fetch('errors_box.html'); $page->tpl->clear_assign('errors_box'); return $ret; } $row = sql_getRow("SELECT * FROM `objects` WHERE id='{$id}' AND client_id='{$userid}'"); if (!$row) { $page->tpl->assign(array('errors' => array('Нет такого объявления или объявление принадлежит не Вам!'))); $ret['errors_box'] = $page->tpl->fetch('errors_box.html'); $page->tpl->clear_assign('errors_box'); return $ret; } if (isset($_POST['fld'])) { $post = $_POST['fld']; if ($post['city'] == 1) { unset($this->req_fields['district_id']); } else { unset($this->req_fields['metro_id']); unset($this->req_fields['metro_time']); unset($this->req_fields['metro_time_type']); } foreach ($this->req_fields as $key => $val) { if (empty($post[$key])) { $errors[] = $this->req_fields[$key]; } } foreach ($post['delphoto'] as $delphoto => $smth) { $this->deletePhoto($delphoto); } foreach ($post['delplan'] as $delplan => $smth) { $this->deletePlan($delplan); } if (isset($_FILES)) { $photo = $plan = array(); foreach ($_FILES['fld'] as $key => $value) { if (isset($value['photo'])) { $photo[$key] = $value['photo']; } if (isset($value['plan'])) { $plan[$key] = $value['plan']; } } include_once 'functions.php'; $dir = 'files/objects/' . $id; if (!is_dir($dir)) { mkdir($dir); chmod($dir, 0775); } if ($photo) { $sizes = array('im_small' => array('50', '36'), 'image_small' => array('250', '250'), 'image_large' => array('640', '480')); $images_photo = downloadFiles($_FILES, count($photo['name']), 'photo', "files/objects/{$id}", $sizes, 85, true); if (!empty($images_photo)) { $ret['files_photo'] = $images_photo; } } if ($plan) { $sizes = array('image_small' => array('50', '36'), 'image_large' => array('640', '480')); $images_plan = downloadFiles($_FILES, count($plan['name']), 'plan', "files/objects/{$id}", $sizes, 85, true); if (!empty($images_plan)) { $ret['files_plan'] = $images_plan; } } } $ret['metro_dest'] = intval($post['select_metro_time']); $ret['metro_dest_text'] = intval($post['select_metro_time_type']); foreach ($post as $key => $val) { $ret[$key] = $post[$key]; } if ($errors) { array_unshift($errors, '<b>Не заполнены следующие поля</b>'); $page->tpl->assign(array('errors' => $errors)); $ret['errors_box'] = $page->tpl->fetch('errors_box.html'); $page->tpl->clear_assign('errors_box'); } else { $this->updateObject($id, $ret); $row = sql_getRow("SELECT * FROM `objects` WHERE `id`='{$id}' AND `client_id`='{$userid}'"); } } $ret = array(); $ret['id'] = $id; $ret['metrostations'] = array('' => '- не выбрано -') + sql_getRows('SELECT id, name FROM `obj_locat_metrostations` WHERE 1 ORDER BY name', true); $ret['districs_mo'] = array('' => '- не выбрано -') + $this->getDistricsAndCities(); $ret['house_type'] = array('' => '- не выбрано -') + sql_getRows('SELECT id, name FROM `obj_housetypes` WHERE 1 ORDER BY id', true); $ret['city_id'] = $row['city_id']; $ret['district_id'] = $row['distrcit_id']; $ret['metro_id'] = $row['metro_id']; $ret['select_metro_time'] = $row['metro_dest_value']; $ret['select_metro_time_type'] = intval($row['metro_dest_text']) + 1; $ret['rooms'] = $row['room']; $ret['addres'] = sql_getValue("SELECT `address` FROM `obj_address` WHERE `id`='" . $row['address_id'] . "'"); $ret['new_house'] = $row['market'] == "first" ? 1 : 0; $ret['storey'] = $row['storey']; $ret['storey_number'] = $row['storeys_number']; $ret['house_type_id'] = $row['house_type']; $ret['total_area'] = $row['total_area']; $ret['live_area'] = $row['living_area']; $ret['kitchen_area'] = $row['kitchen_area']; $ret['lavatory'] = $row['lavatory']; $ret['balcony'] = $row['balcony']; $ret['phones'] = $row['phone']; $ret['description'] = $row['short_description']; $ret['price_rub'] = $row['price_rub']; $profile = $auth->getCurrentUserData(); $ret['fio'] = $profile['fio']; $ret['email'] = $profile['login']; $contact_phones = explode(",", $row['contact_phone']); $ret['phone'] = trim($contact_phones[0]); $ret['phone2'] = trim($contact_phones[1]); $fotki = sql_getRows("SELECT * FROM `obj_elem_images` WHERE `type`='photo' AND `pid`='{$id}'"); foreach ($fotki as $fotka) { $ret['photos'][] = array('id' => $fotka['id'], 'link' => $fotka['imagepath'], 'filename' => substr($fotka['imagepath'], strrpos($fotka['imagepath'], '/') + 1)); } $plans = sql_getRows("SELECT * FROM `obj_elem_plans` WHERE `pid`='{$id}'"); foreach ($plans as $plan) { $ret['plans'][] = array('id' => $plan['id'], 'link' => $plan['image'], 'filename' => substr($plan['image'], strrpos($plan['image'], '/') + 1)); } return $ret; }
function editgetMetro() { $table = get('table', 'objects', 'g'); $district = (int) get('district', 0, 'g'); $id = (int) get('id', 0, 'g'); // Выбираем список метро для данного района и всех его подрайонов $childs = $this->getChilds('obj_locat_districts', 'ORDER BY name', $district); $this->getList($childs, $districts); $districts[$district] = array(); $metro[] = sql_getRow('SELECT * FROM obj_locat_metrostations WHERE id=1'); $metro = array_merge($metro, sql_getRows('SELECT * FROM obj_locat_metrostations WHERE district IN (' . implode(',', array_keys($districts)) . ')')); if ($table == 'objects') { $selected = sql_getValue('SELECT metro_id FROM ' . $table . ' WHERE id=' . $id); } header('Content-Type: text/xml'); echo '<?xml version="1.0" encoding="windows-1251" standalone="yes" ?><body>'; foreach ($metro as $key => $val) { echo '<item><id>' . $val['id'] . '</id><name>' . $val['name'] . '</name><selected>' . (isset($selected) && $selected == $val['id'] ? '1' : '0') . '</selected></item>'; } echo '</body>'; }
function getArchive($file, $clear) { global $settings; require_once 'Tar.php'; $ldbl_files = array('dic_fltfnt.data', 'recs.data'); $ldbl_fields = array('dic_fltfnt.data' => array('id', 'name'), 'recs.data' => array('id', 'dt', 'crdt', 'updt', 'act', 'prc', 'area', 'rgn_id', 'rgn_str', 'str_id', 'str_str', 'bldaddr', 'bldht', 'bldflr', 'farval', 'fltbl_str', 'fltbl_id', 'fartp_id', 'bldtp_id', 'bldtr_id', 'bldel_id', 'fltlv_id', 'fltfr_id', 'fltph_id', 'fltin_id', 'fltov_id', 'fltst_id', 'aptp', 'tlrmqt', 'slrmqt', 'sqtl', 'sqlf', 'sqkt', 'sqdl', 'cm', 'nova', 'mm_id', 'phones', 'photos', 'has_photos', 'price_rub', 'price_usd', 'price_eur', 'agency', 'indicator', 'ipoteka', 'tariff_mask')); function esc_data($val) { return "'" . $val . "'"; } $srv_name = $_SERVER['DOCUMENT_ROOT']; $path = '/files/archives/'; // Подготовим путь к хранению файлов $file_path = $srv_name . $path; // Если нет указанной директории создадим её if (!is_dir($srv_name . $path)) { if (!mkdir($file_path, 0777)) { return "<script>alert('Ошибка при проверки директории для загрузки архива.');</script>"; } } // Временный старый путь к архиву $out_path = $file; // Проверим есть ли архив if (file_exists($out_path)) { $filesize = filesize($out_path); // Проверим его размер if ($filesize > 10000000) { return "<script>alert('Очень большой файл.');</script>"; } } // Новый путь $in_path = $file_path . basename($out_path); // Переместили архив if (copy($out_path, $in_path)) { // Удалили временный архив unlink($out_path); $tar_object = new Archive_Tar($in_path, 'gz'); // Если открыли архив if ($tar_object->extract($file_path . "unpack")) { $files = scandir($file_path . "unpack"); // Архив не пустой if (count($files)) { // Чистим loadable таблицы $sql = "SET NAMES cp1251;\n\t\t\t\t\t\tSET SESSION character_set_database=cp1251;\n\t\t\t\t\t\tTRUNCATE TABLE ldbl_recs_rent;\n\t\t\t\t\t\tTRUNCATE TABLE ldbl_dic_fltfnt;\n\t\t\t\t\t\t"; sql_query($sql); // Блокируем таблицы для работы с ними $sql = "LOCK TABLES ldbl_dic_fltfnt WRITE, ldbl_recs_rent WRITE;"; sql_query($sql); /* foreach ($files AS $file) { if (is_readable($file_path."unpack/".$file)) { if (in_array($file, $ldbl_files)){ $table_name = substr($file, 0, -5); $result = sql_query ('LOAD DATA LOCAL INFILE "'.$file_path."unpack/".$file.'" INTO TABLE ldbl_'.$table_name.' FIELDS TERMINATED BY \'\t\' ENCLOSED BY \'"\' ESCAPED BY \'\\\' LINES TERMINATED BY "\r\n"'); $this->eRror .= (!$result) ? ' Не удалось загрузить файл '.$file.' из архива' : ''; } } else { $this->eRror .= (!$result) ? ' Не удалось прочитать файл '.$file.' из архива' : ''; } } */ foreach ($files as $file) { if (is_readable($file_path . "unpack/" . $file)) { if (in_array($file, $ldbl_files)) { $table_name = substr($file, 0, -5); if ($table_name == 'recs') { $table_name = $table_name . "_rent"; } $stings = file($file_path . "unpack/" . $file); if (count($stings)) { $ii = 0; foreach ($stings as $num => $line) { if ($ii == 0) { $sql_insert = "INSERT INTO ldbl_" . $table_name . " (" . implode(",", $ldbl_fields[$file]) . ") "; $sql_values = " VALUES (" . implode(",", array_map("esc_data", explode("\t", $line))) . "), "; } else { $sql_values .= " VALUES (" . implode(",", array_map("esc_data", explode("\t", $line))) . "), "; } $ii++; if ($ii == 1000) { $sql_values = substr($sql_values, 0, -2) . ";"; $result = sql_query($sql_insert . $sql_values); $this->eRror .= !$result ? ' Ошибки при загрузке файла ' . $file . ' ERROR:(' . $result . ')' : ''; $ii = 0; } } if (!$ii) { $result = sql_query($sql_insert . $sql_values); $this->eRror .= !$result ? ' Ошибки при загрузке файла ' . $file . ' ERROR:(' . $result . ')' : ''; } } } } else { $this->eRror .= !$result ? ' Не удалось прочитать файл ' . $file . ' из архива' : ''; } } sql_query("UNLOCK TABLES;"); if (empty($this->eRror)) { if (!empty($clear)) { sql_query("DELETE FROM `" . $this->table_flat . "` WHERE loadable='1'"); } $ldbl_regions = sql_getRows('SELECT ldbl_recs_rent.*, ldbl_dic_rgn.name FROM `ldbl_recs_rent` LEFT JOIN ldbl_dic_rgn ON ldbl_recs_rent.rgn_id=ldbl_dic_rgn.id WHERE 1 GROUP BY ldbl_recs_rent.rgn_id', true); foreach ($ldbl_regions as $key => $value) { $place = substr(trim($value['name']), -2); switch ($place) { case 'м.': $metro = "м. " . substr(trim($value['name']), 0, -3); $metro_id = (int) sql_getValue("SELECT id FROM `obj_locat_metrostations` WHERE name='{$metro}'"); if (!$metro_id) { $metro_id = 1; } $district_id = 'NULL'; $district_city_id = 'NULL'; break; case 'г.': $district = substr(trim($value['name']), 0, -3); $district = sql_getRow("SELECT id, pid FROM `obj_locat_districts` WHERE name='{$district}' AND coordinat=''"); $district_id = 'NULL'; $district_city_id = 'NULL'; if (!empty($district)) { $district_id = $district['pid']; $district_city_id = $district['id']; } $metro_id = 1; break; default: $district = trim($value['name']); $district = sql_getRow("SELECT id, pid FROM `obj_locat_districts` WHERE name LIKE '%{$district}%'"); $district_id = 'NULL'; $district_city_id = 'NULL'; if (!empty($district)) { $district_id = $district['pid']; $district_city_id = $district['id']; } $metro_id = 1; break; } sql_query("UPDATE ldbl_recs_rent SET district_id='" . $district_id . "', district_city_id='" . $district_city_id . "', metro_id='" . $metro_id . "' WHERE rgn_id='" . $value['rgn_id'] . "'"); } $ldbl_addreses = sql_getRows("SELECT\n\t\t\t\t\t\t\tldbl_recs_rent.*,\n\t\t\t\t\t\t\tCONCAT(\n\t\t\t\t\t\t\t\tIF(ldbl_recs_rent.str_id>0,\n\t\t\t\t\t\t\t\t\tldbl_dic_str.name,\n\t\t\t\t\t\t\t\t\tldbl_recs_rent.str_str\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t' ',\n\t\t\t\t\t\t\t\tbldaddr\n\t\t\t\t\t\t\t) AS address_name,\n\t\t\t\t\t\t\tldbl_dic_rgn.name\n\t\t\t\t\t\tFROM `ldbl_recs_rent`\n\t\t\t\t\t\tLEFT JOIN ldbl_dic_str ON ldbl_recs_rent.str_id=ldbl_dic_str.id\n\t\t\t\t\t\tLEFT JOIN ldbl_dic_rgn ON ldbl_recs_rent.rgn_id=ldbl_dic_rgn.id\n\t\t\t\t\t\tWHERE 1 GROUP BY ldbl_recs_rent.str_id", true); foreach ($ldbl_addreses as $key => $value) { $place = trim(substr($value['name'], -2)); switch ($place) { case 'м.': $address_city = "Москва г."; break; case 'г.': $address_city = $value['name']; break; default: $address_city = $value['name']; break; } //Проверяем адрес в таблице адресов и координат $address = $address_city . ", " . e(strip_tags($value['address_name'])); $address_id = (int) sql_getValue("SELECT id FROM `obj_address` WHERE address='{$address}'"); if (!$address_id) { $address_id = (int) sql_insert('obj_address', array('address' => $address)); } sql_query("UPDATE ldbl_recs_rent SET address_id='" . $address_id . "', address='" . $address . "' WHERE str_id='" . $value['str_id'] . "'"); } $ldbl_phones = sql_getRows("SELECT * FROM `ldbl_recs_rent` WHERE 1 GROUP BY phones", true); foreach ($ldbl_phones as $key => $value) { sql_query("UPDATE ldbl_recs_rent SET mobile_phone='" . $this->getMobileNumber($value['phones']) . "' WHERE phones='" . $value['phones'] . "'"); } // Все готово можно начинать великое переселение ;) // sql для переноса из loadable таблицы в нашу рабочую $sql = "INSERT INTO objects (\n\t\t\t\t\t\t\tvisible,lot_id,market,room,district_id,district_city_id,metro_id,metro_dest_value,metro_dest_text,\n\t\t\t\t\t\t\tobj_type_id,address,short_description,price_dollar,price_rub,create_time,storey,\n\t\t\t\t\t\t\tstoreys_number,house_type,total_area,living_area,kitchen_area,balcony,phone,lavatory,\n\t\t\t\t\t\t\tmoscow,contact_phone,loadable,address_id,status,agent_percent,client_percent,\n\t\t\t\t\t\t\trefrigerator,tv,washing_m,mobile_phone,photos\n\t\t\t\t\t\t)\n\t\t\t\t\t\tSELECT\n\t\t\t\t\t\t1,\n\t\t\t\t\t\t(SELECT MAX(lot_id) FROM objects)+1 AS lot_id,\n\t\t\t\t\t\tIF(ldbl_recs_rent.nova!=0,'first','second') AS market,\n\t\t\t\t\t\tldbl_recs_rent.tlrmqt AS room,\n\t\t\t\t\t\tldbl_recs_rent.district_id,\n\t\t\t\t\t\tldbl_recs_rent.district_city_id,\n\t\t\t\t\t\tldbl_recs_rent.metro_id,\n\t\t\t\t\t\tldbl_recs_rent.farval AS metro_dest_value,\n\t\t\t\t\t\tIF(ldbl_recs_rent.fartp_id!=2,0,1) AS metro_dest_text,\n\t\t\t\t\t\t'room',\n\t\t\t\t\t\tldbl_recs_rent.address,\n\t\t\t\t\t\tldbl_recs_rent.cm AS short_description,\n\t\t\t\t\t\tldbl_recs_rent.price_usd AS price_dollar,\n\t\t\t\t\t\tldbl_recs_rent.price_rub AS price_rub,\n\t\t\t\t\t\tCONCAT(ldbl_recs_rent.crdt, ' 10:00:00') AS create_time,\n\t\t\t\t\t\tldbl_recs_rent.bldht AS storey,\n\t\t\t\t\t\tldbl_recs_rent.bldflr AS storeys_number,\n\t\t\t\t\t\t(SELECT obj_housetypes.id FROM obj_housetypes WHERE LEFT(obj_housetypes.name, 1)=ldbl_dic_bldtp.name) AS house_type,\n\n\t\t\t\t\t\tIF (ldbl_recs_rent.sqtl IS NULL,\n\t\t\t\t\t\t\t'0.0',\n\t\t\t\t\t\t\tIF (ldbl_recs_rent.sqtl mod 10 = 0,\n\t\t\t\t\t\t\t\tldbl_recs_rent.sqtl div 10,\n\t\t\t\t\t\t\t\tCONCAT(ldbl_recs_rent.sqtl div 10, '.', ldbl_recs_rent.sqtl mod 10)\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t) AS total_area,\n\n\t\t\t\t\t\tIF (ldbl_recs_rent.sqlf IS NULL,\n\t\t\t\t\t\t\t'0.0',\n\t\t\t\t\t\t\tIF (ldbl_recs_rent.sqlf mod 10 = 0,\n\t\t\t\t\t\t\t\tldbl_recs_rent.sqlf div 10,\n\t\t\t\t\t\t\t\tCONCAT(ldbl_recs_rent.sqlf div 10, '.', ldbl_recs_rent.sqlf mod 10)\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t) AS living_area,\n\n\t\t\t\t\t\tIF (ldbl_recs_rent.sqkt IS NULL,\n\t\t\t\t\t\t\t'0.0',\n\t\t\t\t\t\t\tIF (ldbl_recs_rent.sqkt mod 10 = 0,\n\t\t\t\t\t\t\t\tldbl_recs_rent.sqkt div 10,\n\t\t\t\t\t\t\t\tCONCAT(ldbl_recs_rent.sqkt div 10, '.', ldbl_recs_rent.sqkt mod 10)\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t) AS kitchen_area,\n\n\t\t\t\t\t\tIF(ldbl_recs_rent.fltbl_id > 1,\n\t\t\t\t\t\t\tIF (ldbl_recs_rent.fltbl_id = 1,\n\t\t\t\t\t\t\t\t'1',\n\t\t\t\t\t\t\t\tIF (ldbl_recs_rent.fltbl_id = 'Б',\n\t\t\t\t\t\t\t\t\t'4',\n\t\t\t\t\t\t\t\t\tIF (ldbl_recs_rent.fltbl_id = 'Л',\n\t\t\t\t\t\t\t\t\t\t'5',\n\t\t\t\t\t\t\t\t\t\tIF (ldbl_recs_rent.fltbl_id = '2Б',\n\t\t\t\t\t\t\t\t\t\t\t'6',\n\t\t\t\t\t\t\t\t\t\t\tIF (ldbl_recs_rent.fltbl_id = '2Л',\n\t\t\t\t\t\t\t\t\t\t\t\t'7',\n\t\t\t\t\t\t\t\t\t\t\t\tIF (ldbl_recs_rent.fltbl_id = 'БЛ',\n\t\t\t\t\t\t\t\t\t\t\t\t\t'8',\n\t\t\t\t\t\t\t\t\t\t\t\t\t'0'\n\t\t\t\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t'0'\n\t\t\t\t\t\t) AS balcony,\n\n\t\t\t\t\t\tIF(ldbl_recs_rent.fltph_id>1,\n\t\t\t\t\t\t\t'1',\n\t\t\t\t\t\t\t'0'\n\t\t\t\t\t\t) AS phone,\n\n\t\t\t\t\t\tIF(ldbl_recs_rent.fltlv_id > 3,\n\t\t\t\t\t\t\t'2',\n\t\t\t\t\t\t\tIF(ldbl_recs_rent.fltlv_id = 2,\n\t\t\t\t\t\t\t\t'1',\n\t\t\t\t\t\t\t\t'0'\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t) AS lavatory,\n\n\t\t\t\t\t\tIF (ldbl_recs_rent.area = 1,\n\t\t\t\t\t\t\t'1',\n\t\t\t\t\t\t\t'0'\n\t\t\t\t\t\t) AS moscow,\n\n\t\t\t\t\t\tphones AS contact_phone,\n\t\t\t\t\t\t'1',\n\t\t\t\t\t\tldbl_recs_rent.address_id,\n\t\t\t\t\t\t'2',\n\t\t\t\t\t\tldbl_recs_rent.commission_agency,\n\t\t\t\t\t\tldbl_recs_rent.commission_client,\n\t\t\t\t\t\tldbl_recs_rent.fltrf_id,\n\t\t\t\t\t\tldbl_recs_rent.flttv_id,\n\t\t\t\t\t\tldbl_recs_rent.fltwh_id,\n\t\t\t\t\t\tldbl_recs_rent.mobile_phone,\n\t\t\t\t\t\tldbl_recs_rent.photos\n\n\t\t\t\t\t\tFROM `ldbl_recs_rent`\n\t\t\t\t\t\tLeft join ldbl_dic_bldtp ON ldbl_recs_rent.bldtp_id = ldbl_dic_bldtp.id\n\t\t\t\t\t\t"; $result = sql_query($sql); // У нас получилось? $this->eRror = $result ? '' : ' Не удалось выполнить перенос данных из временных таблиц в основную.'; } // Удалим распакованные файлы foreach ($files as $file) { unlink($file_path . "unpack/" . $file); } } // Удалим архив unlink($in_path); } if (empty($this->eRror)) { $this->eRror = 'Архив успешно загружен.'; } return "<script>\n\t \tvar err = parent.document.getElementById('error').innerHTML;\n\t parent.document.getElementById('error').innerHTML = '" . e($this->eRror) . "' + err;\n\t </script>"; } else { return "<script>\n\t \tvar err = parent.document.getElementById('error').innerHTML;\n\t parent.document.getElementById('error').innerHTML = 'Не удалось загрузить архив. ' + err;\n\t </script>"; } }
/** * Копирование сайта * @return string */ function editCopy() { $ids = (array) get('id', array(), 'g'); if (!$ids) { echo "<script type='text/javascript'>location.href = '/admin/?page=" . $this->name . "';</script>"; } set_time_limit(60); sql_query('BEGIN'); foreach ($ids as $key => $id) { // Получаем данные по сайту $data = sql_getRow("SELECT * FROM sites WHERE id=" . $id); unset($data['id']); $number = sql_getValue("SELECT COUNT(id) FROM sites WHERE name LIKE '" . $data['name'] . "%'"); $data['name'] .= "_" . $number; // Копируем эти данные в новую строку $new_site_id = sql_insert('sites', $data); if (!is_int($new_site_id)) { sql_query('ROLLBACK'); echo $this->str('error') . ': ' . $new_site_id; die; } // Копируем языки $langs = sql_getRows("SELECT name, descr, locale, charset, priority, root_id FROM sites_langs WHERE pid=" . $id); if (!empty($langs)) { foreach ($langs as $lang_row) { $old_root = $lang_row['root_id']; $new_root_id = (int) sql_getValue("SELECT MIN(root_id) FROM tree WHERE 1") - 1; if ($new_root_id <= 0) { $new_root_id = (int) sql_getValue("SELECT MAX(id) FROM tree WHERE 1") + 1; } $lang_row['pid'] = $new_site_id; $lang_row['root_id'] = $new_root_id; $new_lang_id = sql_insert('sites_langs', $lang_row); if (!is_int($new_lang_id)) { sql_query('ROLLBACK'); echo $this->str('error') . ': ' . $new_lang_id; die; } // Создаем в дереве корневой элемент $tree_row = sql_getRow("SELECT * FROM tree WHERE id=" . $old_root); if (!$tree_row) { sql_query('ROLLBACK'); echo 'no row in tree for root_id=' . $old_root; die; } $tree_row['id'] = $tree_row['pid'] = $tree_row['root_id'] = $new_root_id; $tree_row['pids'] = '/' . $new_root_id . '/'; $tree_row['priority'] = (int) sql_getValue("SELECT MAX(priority) FROM tree WHERE id=pid") + 1; $_id = sql_insert('tree', $tree_row); if (!is_int($_id)) { sql_query('ROLLBACK'); echo $this->str('error') . ': ' . $_id; die; } // Копируем разделы $this->table = 'tree'; $rows = sql_getColumn("SELECT id FROM tree WHERE pid=" . $old_root . " AND id<>pid"); if ($rows) { foreach ($rows as $row) { $this->CopyTree($row, $new_root_id, true); } } $this->Validate(0, '', 0, array(), $new_root_id); $this->table = 'sites'; } } } sql_query('COMMIT'); touch_cache('sites'); touch_cache('tree'); return "<script type='text/javascript'>location.href = '/admin/?page=" . $this->name . "';</script>"; }