Файл: admin.php
Строк: 255
<?php
/*(с) Im !eee*/
if(!file_exists('config.php')){exit('Не найден файл config.php!');}
require 'config.php';
header('Content-Type: text/html; charset=UTF-8');
/*sets vars in config.php file*/
function set_var($nm,$vl,$file,$rw=0,$qt=1){
    $vl=($qt)?'''.$vl.''':$vl;
    $t=preg_replace('~(?<=/*['.$nm.']*/).*(?=/*[/'.$nm.']*/)~i',$vl,($rw)?file_get_contents($file):$file,1);
    if($rw){
        file_put_contents($file, $t);
    } else {
        return $t;
    }
}
$form=array(array(), array(), array(), array()); $ps=&$_POST;
/*form($arr), label1, name1, default_value1*/
function add_trs(&$arr){
    global $ps;
    $ag=func_get_args(); $l=sizeof($ag);
    for($i=1; $i<$l; $i+=3){
        /*$ag[$i] - label $ag[$i+1] - name $ag[$i+2] - default value*/
        $arr[2][]=$ag[$i].'<br/><input type="text" name="'.$ag[$i+1].'" value="';
        $arr[2][]='"><br/>';
        if(isset($ps[$ag[$i+1]])){
            if(get_magic_quotes_gpc()){$ps[$ag[$i+1]]=stripslashes($ps[$ag[$i+1]]);}
            $arr[1][$ag[$i+1]]=sizeof($arr[0]);
        } else {
            $arr[1][$ag[$i+1]]=-1;
        }
        $arr[0][]=$ag[$i+2];
        $arr[3][]=false;
    }
}
/*form($arr), label1, name1, default_value1, a_name_of_text_input_in_the_same_form1, ...*/
function add_chb(&$arr){
    global $ps;
    $ag=func_get_args(); $l=sizeof($ag);
    for($i=1; $i<$l; $i+=4){
        /*$ag[$i] - label $ag[$i+1] - name
         *$ag[$i+2] - default value $ag[$i+3] - "text" input*/
        $arr[2][]=$ag[$i].'<input type="checkbox" name="'.$ag[$i+1].'"';
        $arr[2][]='><br/>';
        if(isset($ps[$ag[$i+3]])){
            $ps[$ag[$i+1]]=(isset($ps[$ag[$i+1]])&&$ps[$ag[$i+1]]=='on')?1:0;
            $arr[1][$ag[$i+1]]=sizeof($arr[0]);
        } else {
            $arr[1][$ag[$i+1]]=-1;
        }
        $arr[0][]=$ag[$i+2];
        $arr[3][]=true;
    }
}
/*prints a form*/
function pr_fm(&$arr, $act, $sb_nm){
    $l=sizeof($arr[0]);
    echo '<form method="POST" action="'.$act.'">';
    for($i=0; $i<$l; $i++){
        echo $arr[2][$i*2].
        (($arr[3][$i])?
        (($arr[0][$i])?'checked="checked"':''):htmlspecialchars($arr[0][$i])).
        $arr[2][$i*2+1];
    }
    echo '<input type="submit" value="'.$sb_nm.'"></form>';
}
/*perform addslashes twice (to make preg_replace happy)*/
function asl($str){
    return addslashes(addslashes($str));
}
/*sets max messages on page if using files*/
function set_fl_mess_tot($new){
    $all=file_get_contents(PG_PREF.'total.txt')+1;
    if($all==1){return;}
    $arr=array(); $p=0; $p2=1;
    while(true){
        while(sizeof($arr)<$new&&$p2<$all){
            $name=PG_PREF.$p2.((file_exists(PG_PREF.$p2.'_.txt'))?'_':'').'.txt';
            $arr=array_merge($arr,array_map('rtrim',file($name)));
            unlink($name);
            $p2++;
        }
        if(sizeof($arr)==0){
            break;
        } else {
            $t=sizeof($arr);
        }
        do{
            $p++;
            if(file_exists(PG_PREF.$p.'.txt')){
                rename(PG_PREF.$p.'.txt', PG_PREF2.$p.'_.txt');
            }
            file_put_contents(PG_PREF.$p.'.txt', join(PHP_EOL, array_splice($arr, 0, $new, array())));
        } while(sizeof($arr)>=$new);
    }
    file_put_contents(PG_PREF.'total.txt', $p);
    file_put_contents(PG_PREF.'last.txt', $t);
}
$me=$_SERVER['PHP_SELF'];
function pr_end(){
    echo '</body></html>';
}
register_shutdown_function('pr_end');
?>
<?php echo '<?xml version="1.0" encoding="utf-8"?>';?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<!- (с) Im !eee  ->
<head>
<meta http-equiv="Content-type" content="text/html;charset=UTF-8"/>
<meta http-equiv="Cache-control" content="no-cache,no-store,must-revalidate"/>
<meta http-equiv="Expires" content="Wed, 26 Feb 1997 8:21:57 GMT"/>
<meta http-equiv="Pragma" content="no-cache"/>
<title>Гостевая книга :: админ-панель</title>
</head>
<body>
<?php 
if(isset($_COOKIE['jsgb_adm_pass']) && $_COOKIE['jsgb_adm_pass']==ADM_PASS){
    $log=true; 
} else {
    $log=false;
    add_trs($form, 'Пароль', 'log_adm_pass', '');
    if($form[1]['log_adm_pass']!=-1){ 
        if(md5($ps['log_adm_pass'])==ADM_PASS){
            setcookie('jsgb_adm_pass', ADM_PASS, time()+60*60*24*10);
            $log=true; 
        }else{
            echo 'Неправильный пароль!<br/>';
        }
    }
} 
if(!$log){ 
    pr_fm($form,$me,'Войти');
    exit;
}
$act=isset($_GET['act'])?$_GET['act']:4;
if($act>5||$act<1){$act=4;}
if($act==5){
    setcookie('jsgb_adm_pass', '', 0);
    exit('Вы вышли.');
}
?>
<p><a href="<?php echo $me?>?act=1">Пароль</a> |
<a href="<?php echo $me?>?act=2">Настройки php</a> |
<a href="<?php echo $me?>?act=3">Настройки html</a> |
<a href="<?php echo $me?>?act=4">Сообщения</a> |
<a href="<?php echo $me?>?act=5">Выход</a>
</p><hr size="1"/>
<?php
if($act==1){
    echo '<b>Изменить пароль администратора</b><br/><br/>';
    add_trs($form, 'Старый пароль', 'o_p', '', 'Новый пароль', 'n_p', '');
    if($form[1]['o_p']!=-1&&$form[1]['n_p']!=-1){
        if(md5($ps['o_p'])==ADM_PASS){
            $t=md5($ps['n_p']);
            setcookie('jsgb_adm_pass', $t, time()+60*60*24*10);
            set_var('adm_pass',$t,'config.php',1);
            echo 'Пароль изменен.<br/>';
        } else {
            echo 'Неправильный пароль.<br/>';
            $form[0][$form[1]['n_p']]=$ps['n_p'];
        }
    }
    pr_fm($form, $me.'?act=1','Изменить');
    exit;
}
if($act==2){
    echo '<b>Настроить php скрипты на сервере</b><br/><br/>';
    add_trs($form,
            'Сообщений на странице', 'mess_tot', MESS_TOT,
            'Максимальная длина имени автора', 'ml_aut', ML_AUT,
            'Максимальная длина сообщения', 'ml_msg', ML_MSG,
            'Ограничение по времени между сообщениями (секунды)', 'tm_wr', TM_WR
            );
    add_chb($form, 'Использовать bb теги', 'use_bb', USE_BB, 'mess_tot');
    add_trs($form, 
            'Хранение данных (mysql или files)', 'store', STORE,
            'Путь к файлам данных (files)', 'pg_pref', PG_PREF,
            'Сервер (mysql)', 'my_host', MY_HOST,
            'Пользователь (mysql)', 'my_user', MY_USER,
            'Пароль (mysql)', 'my_pass', MY_PASS,
            'Имя базы данных (mysql)', 'my_db', MY_DB,
            'Имя таблицы(mysql)', 'my_tbl', MY_TBL
            );
    add_chb($form, 'Создать таблицу (из файла jsgb_posts.sql)', 'crt_tbl', 0, 'mess_tot');
    //print_r($_POST);
    $cont=file_get_contents('config.php');
    if(($t=$form[1]['mess_tot'])!=-1&&$ps['mess_tot']!=MESS_TOT){
        $t2=(int)$ps['mess_tot'];
        if($t2<1){
            echo 'Число сообщений дожно быть больше 0<br/>';
        } else {
            $cont=set_var('mess_tot',$t2,$cont);
            if(STORE=='files'&&is_dir(PG_PREF)){
                set_fl_mess_tot($t2);
            }
            $form[0][$t]=$t2;
        }
    }
    if(($t=$form[1]['ml_aut'])!=-1&&$ps['ml_aut']!=ML_AUT){
        $t2=(int)$ps['ml_aut'];
        if($t2<1){
            echo 'Длина имени автора дожна быть больше 0<br/>';
        } else {
            $cont=set_var('ml_aut',$t2,$cont);
            $form[0][$t]=$t2;
        }
    }
    if(($t=$form[1]['ml_msg'])!=-1&&$ps['ml_msg']!=ML_MSG){
        $t2=(int)$ps['ml_msg'];
        if($t2<1){
            echo 'Длина сообщения дожна быть больше 0<br/>';
        } else {
            $cont=set_var('ml_msg',$t2,$cont);
            $form[0][$t]=$t2;
        }
    }
    if(($t=$form[1]['tm_wr'])!=-1&&$ps['tm_wr']!=TM_WR){
        $t2=(int)$ps['tm_wr'];
        $cont=set_var('tm_wr',$t2,$cont);
        $form[0][$t]=$t2;
    }
    if(($t=$form[1]['use_bb'])!=-1&&$ps['use_bb']!=USE_BB){
        $cont=set_var('use_bb',$ps['use_bb'],$cont);
        $form[0][$t]=$ps['use_bb'];
    }
    $store=STORE;
    if(($t=$form[1]['store'])!=-1&&$ps['store']!=STORE){
        $t2=$ps['store'];
        if($t2!='mysql'&&$t2!='files'){
            echo 'Неизвестный способ хранения<br/>';
        } else {
            $cont=set_var('store',$t2,$cont);
            $form[0][$t]=$t2;
            $store=$t2;
        }
    }
    if(($t=$form[1]['pg_pref'])!=-1&&$ps['pg_pref']!=PG_PREF){
        $t2=$ps['pg_pref'];
        while($t2[strlen($t2)-1]=='\'||$t2[strlen($t2)-1]=='/'){
                    $t2=substr($t2,0,-1);
                }
        $cont=set_var('pg_pref',asl($t2),$cont);
        $form[0][$t]=$t2.DIRECTORY_SEPARATOR;
        if($store=='files'){
            if(!is_dir($t2)){
                echo 'Неправильный путь к файлам<br/>';
            } else {
                if(!file_exists($t2.'total.txt')){
                    file_put_contents($t2.'total.txt', 0);
                }
                if(!file_exists($t2.'lock.txt')){
                    file_put_contents($t2.'lock.txt', '');
                }
                if(!file_exists($t2.'last.txt')){
                    file_put_contents($t2.'last.txt', 0);
                }
            }
        }
    }
    $conn=false;
    if(($t=$form[1]['my_host'])!=-1&&($t1=$form[1]['my_user'])!=-1&&($t2=$form[1]['my_pass'])!=-1){
        if($ps['my_host']!=MY_HOST||$ps['my_user']!=MY_USER||$ps['my_pass']!=MY_PASS){
            $cont=set_var('my_host',asl($ps['my_host']),$cont);
            $form[0][$t]=$ps['my_host'];
            $cont=set_var('my_user',asl($ps['my_user']),$cont);
            $form[0][$t1]=$ps['my_user'];
            $cont=set_var('my_pass',asl($ps['my_pass']),$cont);
            $form[0][$t2]=$ps['my_pass'];
        }
        if($store=='mysql'){
            $conn=mysql_connect($ps['my_host'],$ps['my_user'],$ps['my_pass']);
            if($conn===false){
                echo 'Невозможно подключиться к серверу MySQL<br/>';
            }
        }
    }
    if(($t=$form[1]['my_db'])!=-1){
        $t2=$ps['my_db'];
        if($t2!=MY_DB){
            $cont=set_var('my_db',asl($t2),$cont);
            $form[0][$t]=$t2;
        }
        if($conn!==false){
            if(!mysql_select_db($t2)){
                echo 'Невозможно использовать заданную базу данных<br/>';
            }
        }
    }
    if(($t=$form[1]['my_tbl'])!=-1){
        $t2=$ps['my_tbl'];
        if($t2!=MY_TBL){
            $cont=set_var('my_tbl',asl($t2),$cont);
            $form[0][$t]=$t2;
        }
        if($conn!==false){
            if($form[1]['crt_tbl']!=-1&&$ps['crt_tbl']){
                if(!file_exists('jsgb_posts.sql')){
                    echo 'Не найден файл jsgb_posts.sql, необходимый для создания таблицы<br/>';
                } else {
                    if(!mysql_query(set_var('my_tbl', '`'.$t2.'`', file_get_contents('jsgb_posts.sql'), 0, 0))){
                       echo 'Невозможно создать таблицу<br/>';
                    }
                }
            }
            if(!mysql_query('SELECT `id`,`auth`,`date`,`post` FROM `'.$t2.'` LIMIT 1')){
                echo 'Невозможно использовать заданную таблицу<br/>';
            }
        }
    }
    file_put_contents('config.php', $cont);
    pr_fm($form, $me.'?act=2','Изменить');
    exit;
}
if($act==3){
    $tpth='http://'.$_SERVER['SERVER_NAME'].$_SERVER['PHP_SELF'];
    $tpth=substr($tpth, 0, strrpos($tpth, '/')+1);
    echo '<b>Редактировать пути в файлах html</b><br/><br/>';
    add_trs($form,'index.html - msg_loader.php','ind_path',$tpth.'msg_loader.php');
    add_chb($form,'Редактировать', 'ind_edit',0,'ind_path');
    add_trs($form,'write.html - msg_writer.php','write_path',$tpth.'msg_writer.php');
    add_chb($form,'Редактировать', 'write_edit',0,'ind_path');
    add_trs($form,'main.html - msg_counter.php','count_path',$tpth.'msg_counter.php');
    add_chb($form,'Редактировать', 'count_edit',0,'ind_path');
    add_trs($form,'Ссылка на главную страницу','main_path','/');
    add_chb($form,'В файле index.html', 'mn_ind_ed',0,'ind_path');
    add_chb($form,'В файле write.html', 'mn_wr_ed',0,'ind_path');
    if($form[1]['ind_edit']!=-1&&$ps['ind_edit']&&($t=$form[1]['ind_path'])!=-1){
        $form[0][$t]=$ps['ind_path'];
        if(!file_exists('index.html')){
            echo 'Не найден файл index.html<br/>';
        } else {
            echo 'Путь в файле index.html указан<br/>';
            set_var('path', $ps['ind_path'], 'index.html', 1);
        }
    }
    if($form[1]['write_edit']!=-1&&$ps['write_edit']&&($t=$form[1]['write_path'])!=-1){
        $form[0][$t]=$ps['write_path'];
        if(!file_exists('write.html')){
            echo 'Не найден файл write.html<br/>';
        } else {
            echo 'Путь в файле write.html указан<br/>';
            set_var('path', $ps['write_path'], 'write.html', 1);
        }
    }
    if($form[1]['count_edit']!=-1&&$ps['count_edit']&&($t=$form[1]['count_path'])!=-1){
        $form[0][$t]=$ps['count_path'];
        if(!file_exists('main.html')){
            echo 'Не найден файл main.html<br/>';
        } else {
            echo 'Путь в файле main.html указан<br/>';
            set_var('path', $ps['count_path'], 'main.html', 1);
        }
    }
    if(($t=$form[1]['main_path'])!=-1){
        $form[0][$t]=$ps['main_path'];
        $str='-><a href="'.$ps['main_path'].'">На главную</a><!-';
        if($form[1]['mn_ind_ed']!=-1&&$ps['mn_ind_ed']){
            if(!file_exists('index.html')){
                echo 'Не найден файл index.html<br/>';
            } else {
                echo 'Путь в файле index.html указан<br/>';
                                file_put_contents('index.html', preg_replace('~(?<=<!-/*[main]*/-><a href=").*(?="[^>]*>)~i', asl($ps['main_path']), file_get_contents('index.html')));
            }
        }
        if($form[1]['mn_wr_ed']!=-1&&$ps['mn_wr_ed']){
            if(!file_exists('write.html')){
                echo 'Не найден файл write.html<br/>';
            } else {
                echo 'Путь в файле write.html указан<br/>';
                file_put_contents('write.html', preg_replace('~(?<=<!-/*[main]*/-><a href=").*(?="[^>]*>)~i', asl($ps['main_path']), file_get_contents('write.html')));
            }
        }
    }
    pr_fm($form, $me.'?act=3','Ок');
    exit;
}
if($act==4){ 
    include STORE.'.php'; 
    function ex_hn($val='Ошибка обработки данных'){
        echo '<br/>'.$val;
        rel_lock();
    } 
    if(isset($_GET['msg_scr'])){
        lock('w');
        if($_GET['msg_scr']==1){
            $a=''; $m=''; $ed=0;
            $fpath=$me.'?act=4&msg_scr=1';
            if(isset($_GET['p'],$_GET['n'])){
                $ed=1;
                $p=$_GET['p']; $n=$_GET['n'];
                list($a,$d,$m)=get_mes($p,$n);
                $fpath.='&p='.$p.'&n='.$n;
            }
            add_trs($form, 'Автор', 'a', $a,
                'Сообщение', 'm', $m
                );
            if($ed){
                add_trs($form, 'Дата', 'd', date('d-m-Y H:i:s',$d));
                if(($t1=$form[1]['a'])!=-1&&($t2=$form[1]['d'])!=-1&&($t3=$form[1]['m'])!=-1){
                    ed_m($p, $n, ($ps['a']=='')?' ':$ps['a'], (int)strtotime($ps['d']), ($ps['m']=='')?' ':$ps['m']);
                    echo 'Сообщение изменено<br/>';
                    $form[0][$t1]=$ps['a'];
                    $form[0][$t2]=$ps['d'];
                    $form[0][$t3]=$ps['m'];
                }
            } else {
                if($form[1]['a']!=-1&&$form[1]['m']!=-1){
                    wr(nl2br(($ps['a']=='')?' ':$ps['a']), nl2br(($ps['m']=='')?' ':$ps['m']));
                    echo 'Сообщение добавлено<br/>';
                }
            }
            rel_lock();
            pr_fm($form, $fpath, ($ed)?'Изменить':'Добавить');
        } else if($_GET['msg_scr']==2&&isset($_GET['p'],$_GET['n'])){
            del_m($p=$_GET['p'], $_GET['n']);
            echo 'Сообщение удалено<br/>';
            $ed=1;
        }
        echo '<br/><a href="'.$me.'?act=4'.(($ed)?'&p='.$p:'').'">Назад</a>';
    } else {
        lock('r');
                $np=p_num();
                echo '<b>Сообщения</b><br/><a href="'.$me.'?act=4&msg_scr=1">[Написать]</a>';
        if($np==0){
            exit(ex_hn('Сообщений нет'));
        }
        $n=isset($_GET['p'])?$_GET['p']:1; $l=0;
        $arr=m_on_p(&$n, &$l);
        rel_lock();
        for($i=0;$i<$l;$i++){
            echo '<p>'.$arr[0][$i].'('.date('d.m.Y H:i:s',$arr[1][$i]).')<br/>'.$arr[2][$i].'</p> <a href="'.$me.'?act=4&msg_scr=1&p='.$n.'&n='.$i.'">[Редактировать]</a> <a href="'.$me.'?act=4&msg_scr=2&p='.$n.'&n='.$i.'">[Удалить]</a><br/><hr size="1"/>';
        }
        for($i=1;$i<=$np;$i++){
            if($i==$n){
                echo ' <b>'.$i.'</b>';
            } else {
                echo ' <a href="'.$me.'?act=4&p='.$i.'">'.$i.'</a>';
            }
        }
        echo '</p>';
    }
    exit;
}
?>