/** * Копирование сайта * @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>"; }
/** * Сохранение нового комментария * @param string $text - текст комментария * @param int $user_id - ID пользователя * @param int $pid - ID родительского комментарий * @param string $name - имя пользователя, если $user_id пустое * @return mixed */ function newComment($text, $user_id, $pid = 0, $name = '') { $page =& Registry::get('TPage'); $moderate = (int) $page->tpl->messages['publications_comment_moderate']; $data = array('pid' => $pid ? $pid : 'NULL', 'publication_id' => $this->_id, 'user_id' => $user_id ? $user_id : 'NULL', 'date' => date('Y-m-d H:i:s'), 'name' => $name, 'text' => $text, 'visible' => $moderate ? 0 : 1); $id = sql_insert($this->_table_comments, $data); touch_cache($this->_table_comments); return $id; }
function upload() { $file = $_POST['file']; if (substr($file, 0, strlen('@temp')) == '@temp') { $file = substr($file, strlen('@temp')); } if (!$file || !is_file($file)) { return '<script>alert("Файл потеряли")</script>'; } if (!($config = $this->get_config())) { return "<SCRIPT>alert('" . $this->str('err_no_config') . "')</SCRIPT>"; } require 'modules/csv_tools/Bs_CsvUtil.class.php'; $Bs_CsvUtil =& new Bs_CsvUtil(); $fInfo = pathinfo($file); # gzip decode if ($fInfo["extension"] == "gz") { $zp = gzopen($file, "rb"); if ($zp) { while ($buf = gzread($zp, 65535)) { $data .= $buf; } gzclose($zp); } else { $err = "# err: gzopen"; } $data = $Bs_CsvUtil->csvStringToArray($data, ';', 'both', TRUE, FALSE, TRUE); } elseif ($fInfo["extension"] == "zip" && @function_exists("zip_open")) { $zip = zip_open($file); if ($zip) { // while ( // читаем только первый файл в архиве $zip_entry = zip_read($zip); //) { if (zip_entry_open($zip, $zip_entry, "r")) { $data = zip_entry_read($zip_entry, zip_entry_filesize($zip_entry)); zip_entry_close($zip_entry); } //} zip_close($zip); } $data = $Bs_CsvUtil->csvStringToArray($data, ';', 'both', TRUE, FALSE, TRUE); } else { $data = $Bs_CsvUtil->csvFileToArray($file, ';', 'both', TRUE, FALSE, TRUE); } if (!count($data)) { return '<script>alert("Пустой файл")</script>'; } $errs = 0; if (count($data[count($data) - 1]) == 1) { unset($data[count($data) - 1]); } foreach ($data as $i => $row) { if (count($row) == count($config['fields_request'])) { // готовим WHERE $where = array(); foreach ($config['keys'] as $n => $w) { $where[] = $w . '=' . '"' . $row[$n] . '"'; } $where = ' WHERE ' . implode(' AND ', $where); $n = 0; $comma = ''; $sql = ''; foreach ($config['fields_request'] as $field) { $value = $row[$n] == '"' ? '' : strtr($row[$n], array('\\r' => "\r", '\\n' => "\n")); $_row[$field] = $value; $sql .= $comma . $field . "='{$value}'"; $n++; $comma = ', '; } //echo "SELECT ".implode(',',$config['keys'])." FROM ".$config['table_base'].$where.'<br>'; if (sql_getRow("SELECT " . implode(',', $config['keys']) . " FROM " . $config['table_base'] . $where)) { $sql = 'UPDATE ' . $config['table_base'] . ' SET ' . $sql . $where; } else { $sql = 'INSERT ' . $config['table_base'] . ' SET ' . $sql; } //echo $sql."<br>"; if ($res = sql_query($sql)) { //echo "$i "; } else { echo "<br>строка " . ($i + 1) . " ошибка: " . mysql_error() . '<br>'; echo 'SQL was:' . $sql . '<br>'; $errs++; } } else { echo '<br>Неправильная строка ' . ($i + 1) . ' ' . htmlspecialchars(implode(' ', $row)); $errs++; } } echo "<br>---------------------------------------<br>\n\t\tОбработано " . ($i + 1) . " строк, из них неудачно: {$errs}"; unlink($_FILES['file']['tmp_name']); touch_cache($config['table_base']); }
function EditClearCTR() { $ids = get('id', array(), 'p'); if (!$ids) { return "<script>alert('" . $this->str('e_no_items') . "');</script>"; } $res = sql_query('UPDATE ' . $this->table . ' SET views=0, clicks=0 WHERE id IN (' . join(',', $ids) . ')'); if (sql_getError()) { return $this->Error(sql_getError()); } touch_cache($this->table); return "<script>alert('" . $this->str('ctr_cleared') . "');window.parent.location.reload();</script>"; }
/** * Сохранение голоса в БД * @param $id * @param $item * @param array $free * * @return int|bool */ function saveVote($id, $item, $free) { $catalog = get('catalog', array(), 'p'); sql_query('BEGIN'); include_once PATH_COMMON . '/classes/geo.php'; $geo = new Geo(array('dbname' => $this->geo_dbname, 'tablename' => $this->geo_tablename)); $real_ip = $geo->get_ip(); $ip_data = $geo->get_value(); $columns = sql_getRows("SHOW COLUMNS FROM `" . $this->table_users . "`", true); if (!isset($columns['region'])) { sql_query("ALTER TABLE `" . $this->table_users . "` ADD region VARCHAR( 255 ) NOT NULL;"); } if (!isset($columns['city'])) { sql_query("ALTER TABLE `" . $this->table_users . "` ADD city VARCHAR( 255 ) NOT NULL;"); } if (!isset($columns['district'])) { sql_query("ALTER TABLE `" . $this->table_users . "` ADD district VARCHAR( 255 ) NOT NULL;"); } if (!isset($columns['country'])) { sql_query("ALTER TABLE `" . $this->table_users . "` ADD country VARCHAR( 255 ) NOT NULL;"); } // Добавим в список нового проголосовавшего $user_id = sql_insert($this->table_users, array('id_survey' => $id, 'ip' => $real_ip, 'city' => $ip_data['city'], 'region' => $ip_data['region'], 'district' => $ip_data['district'], 'country' => $ip_data['country'])); if (!is_int($user_id)) { sql_query('ROLLBACK'); return false; } touch_cache($this->table_users); // Если пришли оветы в свободной форме if ($free) { foreach ($item as $val) { foreach ($val as $k => $id_var) { if (array_key_exists($id_var, $free)) { $_id = sql_insert($this->table_free, array('id_variant' => (int) $id_var, 'id_user' => $user_id, 'text' => $free[$id_var])); if (!is_int($_id)) { sql_query('ROLLBACK'); return false; } touch_cache($this->table_free); } } } } // Список вопросов $rows = sql_getRows("SELECT id FROM " . $this->table_quests . " WHERE id_survey=" . $id); // Запишем результат в лог foreach ($rows as $k => $v) { foreach ($item[$v] as $variant) { $_id = sql_insert($this->table_log, array('id_survey' => $id, 'id_quest' => $v, 'id_variant' => $variant, 'id_user' => $user_id, 'text' => isset($free[$variant]) ? $free[$variant] : '')); if (!is_int($_id)) { sql_query('ROLLBACK'); return false; } touch_cache($this->table_log); } foreach ($catalog[$v] as $k => $variant) { $_id = sql_insert($this->table_log, array('id_survey' => $id, 'id_quest' => $v, 'id_variant' => $k, 'id_user' => $user_id, 'text' => $variant)); if (!is_int($_id)) { sql_query('ROLLBACK'); return false; } touch_cache($this->table_log); } } $query = 'UPDATE ' . $this->table . ' SET answ_cnt=answ_cnt+1 WHERE id =' . $id; sql_query($query); touch_cache($this->table); sql_query('COMMIT'); return $user_id; }
function delObjects() { $clients_ids = $_POST['id']; if (!$clients_ids) { return "<script>alert('Ќет выбранных клиентов!');</script>"; } $objects_ids = sql_getColumn('SELECT id FROM objects WHERE client_id IN ("' . join('", "', $clients_ids) . '")'); if (!$objects_ids) { return "<script>alert('ќбъекты дл¤ выбранных клиентов не найдены!');</script>"; } $sql = "DELETE FROM objects WHERE id IN ('" . join("', '", $objects_ids) . "')"; sql_query($sql); $err = sql_getError(); if (!empty($err)) { return "<script>alert('ќшибка: " . e($err) . "');</script>"; } require_once 'modules/objects_func.php'; objects_deleteImages($objects_ids); touch_cache('objects'); return "<script>alert('”спешно удалено!'); window.parent.location.reload();</script>"; }
function Delete() { $id = !empty($_GET['id']) ? (int) $_GET['id'] : 0; $pid = sql_getValue("SELECT pid FROM " . $this->table . " WHERE id=" . $id); $res = sql_query("UPDATE " . $this->table . " SET visible=-1 WHERE id=" . $id); # проставляем next if ($res) { $count = (int) sql_getValue("SELECT COUNT(*) FROM " . $this->table . " WHERE pid=" . $pid . " AND visible>=0"); sql_query("UPDATE " . $this->table . " SET next=" . $count . " WHERE id=" . $pid); if (!$count) { $pid = sql_getValue("SELECT pid FROM " . $this->table . " WHERE id=" . $pid); } touch_cache($this->table); } return "<script>location.href='/admin/?page=" . $this->name . "&id=" . $pid . "';</script>"; }
function getFile($file) { //читаем файл $GLOBALS['gzip'] = false; require_once 'Excel/reader.php'; $data = new Spreadsheet_Excel_Reader(); $data->setOutputEncoding('CP1251'); $data->read($file); $this->_numCols = $data->sheets[0]['numCols']; $this->_numRows = $data->sheets[0]['numRows']; $this->_rows =& $data->sheets[0]['cells']; if (empty($this->_rows)) { $this->Error("Полученный файл пуст."); } echo "<script>var msg_div = parent.document.getElementById('msg_div');</script>"; ob_end_flush(); flush(); //получаем заголовки колонок $this->_Headers = $this->_rows[$this->sRow - 1]; $this->_cHeaders = count($this->_Headers); //создаем временную таблицу $sql = "CREATE TEMPORARY TABLE IF NOT EXISTS tmp_flat (\n \t\t`rooms` INT(11),\n \t\t`metro_id` INT(11),\n \t\t`distance` INT(11),\n \t\t`distance_type` ENUM('foot','transport'),\n \t\t`street` VARCHAR(255),\n \t\t`storey` TINYINT(3),\n \t\t`storeys_number` TINYINT(3),\n \t\t`house_type` INT(11),\n \t\t`total_area` FLOAT(5,1),\n \t\t`living_area` FLOAT(5,1),\n \t\t`kitchen_area` FLOAT(5,1),\n \t\t`balcony` VARCHAR(16),\n \t\t`price_rub` DOUBLE(15,2),\n \t\t`price_dollar` DOUBLE(15,2),\n \t\t`price_euro` DOUBLE(15,2))"; sql_query($sql); $sql = "CREATE TEMPORARY TABLE IF NOT EXISTS tmp_metrostations (\n \t\t`id` INT(11),\n \t\t`name` VARCHAR(255));"; sql_query($sql); $sql = "INSERT INTO tmp_metrostations (name) SELECT name FROM flat_csv_metrostations"; sql_query($sql); sql_query("TRUNCATE TABLE `flat_csv_metrostations`"); $empty = 0; for ($this->_cRow = $this->sRow; $this->_cRow <= $this->_numRows; $this->_cRow++) { unset($row); if ($this->_rows[$this->_cRow][1] != '' && $this->_rows[$this->_cRow][5] != '' && $this->_rows[$this->_cRow][7] != '') { $metro = substr($this->_rows[$this->_cRow][2], -2) == 'м.' ? substr($this->_rows[$this->_cRow][2], 0, -3) : $this->_rows[$this->_cRow][2]; $metro_id = (int) sql_getValue("SELECT id FROM `flat_csv_metrostations` WHERE name='{$metro}'"); if (!$metro_id) { $metro_id = sql_insert('flat_csv_metrostations', array('name' => $metro)); } $house = explode("/", substr($this->_rows[$this->_cRow][5], 0, -1)); $area = explode("/", $this->_rows[$this->_cRow][6]); $row = array('rooms' => $this->_rows[$this->_cRow][1], 'metro_id' => $metro_id, 'distance' => (int) substr($this->_rows[$this->_cRow][3], 0, -1), 'distance_type' => substr($this->_rows[$this->_cRow][3], -1) == 'п' ? 'foot' : 'transport', 'street' => $this->_rows[$this->_cRow][4], 'storey' => $house[0], 'storeys_number' => $house[1], 'house_type' => $this->_house_type[substr($this->_rows[$this->_cRow][5], -1)], 'total_area' => isset($area[0]) ? $area[0] : 0, 'living_area' => isset($area[1]) ? $area[1] : 0, 'kitchen_area' => isset($area[2]) ? $area[2] : 0, 'price_rub' => str_replace(" ", "", substr($this->_rows[$this->_cRow][7], 0, -1)), 'price_dollar' => str_replace(" ", "", substr($this->_rows[$this->_cRow + 1][7], 0, -1)), 'price_euro' => str_replace(" ", "", $this->_rows[$this->_cRow + 2][7])); $this->_cRow = $this->_cRow + 2; //Инсертим во временную таблицу $id = sql_insert('tmp_flat', $row); if (!is_int($id)) { $this->Error("insert into tmp_flat<br />" . $id); } } else { $empty++; } } //Если все в порядке перемещаем данные в рабочую таблицу if (empty($this->eRror)) { sql_query("TRUNCATE TABLE `flat_csv`"); $sql = "INSERT INTO flat_csv (\n\t\t\t\trooms,metro_id,distance,distance_type,street,storey,storeys_number,house_type,total_area,living_area,kitchen_area,price_rub,price_dollar,price_euro\n\t\t\t) \n\t\t\tSELECT \n\t\t\t\trooms,metro_id,distance,distance_type,street,storey,storeys_number,house_type,total_area,living_area,kitchen_area,price_rub,price_dollar,price_euro\n\t\t\tFROM tmp_flat"; sql_query($sql); } else { sql_query("TRUNCATE TABLE `flat_csv_metrostations`"); $sql = "INSERT INTO flat_csv_metrostations (name) SELECT name FROM tmp_metrostations"; sql_query($sql); } touch_cache('flat_csv'); // if (empty($this->eRror)) $this->eRror = 'Успешно завершено!'.' пустых записей:'.$empty; if (empty($this->eRror)) { $this->eRror = 'Успешно завершено!'; } $table_status = sql_getRow("SHOW TABLE STATUS LIKE 'flat_csv'"); return "<script>\n parent.document.getElementById('msg_div').innerHTML = '';\n parent.document.getElementById('a1').innerHTML = '" . $table_status['Update_time'] . "';\n parent.document.getElementById('a2').innerHTML = '" . $table_status['Rows'] . "';\n parent.document.getElementById('error').innerHTML = '" . e($this->eRror) . "';\n </script>"; }
function editRefresh() { $a = file("http://export.rbc.ru/free/cb.0/free.fcgi?period=DAILY&tickers=USD&d1=" . date('j') . "&m1=" . date('n') . "&y1=" . date('Y') . "&separator=%3B&data_format=BROWSER"); if (empty($a)) { return "<script>alert('Сервер с валютами временно недоступен');</script>"; } $a = split(";", $a[0]); $value = $a[5]; $sql = 'UPDATE ' . $this->table . ' SET value="' . $value . '" WHERE name="USD"'; sql_query($sql); $err = sql_getError(); if (!$err) { touch_cache('currencies'); return "<script>alert('" . $this->str('saved') . "'); window.parent.location.reload();</script>"; } return "<script>alert('" . $this->str('error') . ": " . mysql_escape_string($err) . "')</script>"; }
function _log($sql = false, $id = false) { if (!$id && !empty($sql)) { // опледеляем, какой у нас идет запрос, и нужно ли его записать в log_change // в лог записываются только те запросы, которые указаны в глобавльной переменной $log_change_actions static $transaction; static $table; global $log_change_actions, $log_change_exclude_tables; $sql = trim($sql); if (!empty($transaction) || preg_match("/^begin/i", $sql)) { preg_match("/^\\s*(\\w*(\\s*INTO)?)\\s+(.*)/im", $sql, $res); // берем action - в $res[1] // теперь ищем таблицу она будет в ret[2] if (isset($res[1])) { $act = strtoupper($res[1]); } if (isset($act) && in_array($act, $log_change_actions)) { if ($act == 'SELECT' || $act == 'DELETE') { preg_match("/FROM\\s+(`)?(\\w+)(`)?\\s+/im", $res[3], $ret); } else { preg_match("/(`)?(\\w+)(`)?/im", $res[3], $ret); } if (!empty($ret[2])) { $table[] = $ret[2]; } } $transaction .= $sql . "<br>\n "; if (preg_match("/^commit/i", $sql)) { mysql_query("INSERT INTO log_change (user, object, action, description) VALUES (\n\t\t\t\t\t\t\t\"" . (isset($GLOBALS['user']['login']) ? $GLOBALS['user']['login'] : '******') . "\",\n\t\t\t\t\t\t\t\"" . implode(',', $table) . "\",\n\t\t\t\t\t\t\t'TRANSACTION',\n\t\t\t\t\t\t\t\"" . mysql_escape_string($transaction) . "\" )"); $id = mysql_insert_id(); $transaction = ''; } elseif (preg_match("/^rollback/i", $sql)) { $transaction = ''; } } else { preg_match("/^\\s*(\\w*(\\s*INTO)?)\\s+(.*)/im", $sql, $res); // берем action // res[1] - это action (SELECT, UPDATE ....) // res[3] - остаток запроса if (isset($res[1])) { $act = strtoupper($res[1]); } if (isset($act) && in_array($act, $log_change_actions)) { // теперь ищем таблицу она будет в ret[2] if ($act == 'SELECT' || $act == 'DELETE') { preg_match("/FROM\\s+(`)?(\\w+)(`)?\\s+/im", $res[3], $ret); } else { preg_match("/(`)?(\\w+)(`)?/im", $res[3], $ret); } if (isset($ret[2])) { $table[0] = $ret[2]; } // ненужные таблицы не записываем в лог if (!empty($table[0]) && !in_array($table[0], $log_change_exclude_tables)) { mysql_query("INSERT INTO log_change (user, object, action, description) VALUES (\n\t\t\t\t\t\t\t\t\"" . (isset($GLOBALS['user']['login']) ? $GLOBALS['user']['login'] : '******') . "\",\n\t\t\t\t\t\t\t\t\"" . (!empty($table[0]) ? $table[0] : 'UNKNOWN') . "\",\n\t\t\t\t\t\t\t\t'" . (isset($act) ? $act : 'UNKNOWN') . "',\n\t\t\t\t\t\t\t\t\"" . mysql_escape_string($sql) . "\" )"); $id = mysql_insert_id(); } } } //обновляем время последнего доступа к таблицам if (in_array($act, array('DELETE', 'UPDATE', 'REPLACE', 'INSERT'))) { foreach ($table as $k => $v) { touch_cache($v); } } } else { // если запрос был не выполнен, то запись о нем изменяем // мы разнесли это от обработки чтобы не испортить mysql_insert_id // поэтому мы сначала вносим изменения в лог, а потом делаем сам запрос, а потом проверяем, был ли он успешным mysql_unbuffered_query("UPDATE log_change SET action ='ERROR' , description=CONCAT(description,' <br>" . mysql_escape_string(mysql_error()) . "') WHERE id=" . $id); } return $id; }