[ Поиск ] - [ Пользователи ] - [ Календарь ]
Полная Версия: Сохранение коментариев в .dat
Гость_Сергей
Добрый день, вообщем есть скрипт комментариев на сайте. Он сохраняет фалы в папку, для каждой страницы свой отдельный 1страница.dat, 2страница.dat и т.д файл, а нужно сделать хранение всех комментариев в одном общем все страницы.dat файле

[code]
<?php
class ecomment {
//основные настройки
private $store = '/comments/'; //путь до директории хранения файлов с комментариями. Директория должна существовать и иметь достаточные права доступа.
private $moderate = false; //премодерация - если true, то сообщения попадают в публичный список только после утверждения модератором.
private $notify = true; //уведомление о новых комментах

private $password = 'admin'; //пароль администратора. Рекомендуется сменить после установки.
private $salt = '8f56eeedf73175082f8f4c4fceef4f86'; //секретный ключ шифрования. Желательно сменить перед началом использования скрипта.
private $query = 'primer'; //переменные из запроса, которые могут определять уникальность страницы (через запятую)
private $rating = false; //включение оценок сообщений

private $max_length = 1024; //максимальная длинна сообщения (0 для отключения)
private $cpp = 3; //комментариев на страницу
private $include_answers = true; //учитывать в колличестве комментов на страницу ответы. false - только комментарии, не являющиеся ответами на другие комменты
private $gravatar_size = '60'; //размер граватара к комменту.
private $gravatar_default = 'mm'; //путь картинки по умолчанию для граватара (оставьте пустые кавычки, если нужно использовать родную дефолтную картинку граватара)
//по умолчанию все комменты сортируются по дате добавления - сначала старые, потом свежие.
private $total_reverse = false; //реверс последовательности всего списка комментариев
private $page_reverse = false; //реверс комментов на странице
private $from_last_page = true; //показывать последнюю страницу комментариев
private $pagination_top = true; //отображать пагинацию сверху списка комментов
private $pagination_bottom = true; //отображать пагинацию снизу
//уведомления о новых комментариях отправляются только при включенной премодерации
private $mail_subject = 'Отзыв к сайту'; //заголовок письма с уведомлением о новом комментарии
private $mail_target = 'design-minsk@tut.by'; //адреса, на которые будут отправляться уведомления (через запятую)
private $mail_sender_name = 'Нотификатор'; //имя отправителя

private $answer_allowed = false; //разрешить отвечать на комментарии
private $answer_only_top = false; //разрешено отвечать только на комменты первого уровня


private $version = '1.5.5d'; //версия скрипта
//a - добавлен ограничитель $answer_only_top
//b - исправлен баг построения дерева комментов при инициализации (не было вложенности)
//c - включение уведомлений вынесено в отдельную настройку; добавил имя отправителя в настройки
//d - поправлена инициализация по ссылке; закрыта очередная порция ERROR_NOTICE

function ecomment(){
$this->__construct();
}

function __construct($op = ''){
//задаем константы
define('RPATH', realpath($_SERVER['DOCUMENT_ROOT']).'/');
define('STORE', RPATH.$this->store);

$this->post = filter_var_array($_REQUEST);
if(get_magic_quotes_gpc()){
foreach($this->post as $key=>$value) $this->post[$key] = stripslashes($value);
}

//соблюдение стандарта о нумерации страниц:
//"пользователь нумерует от 1, в системе - от 0"
if(!isset($this->post['ecomment_page'])){
if($this->from_last_page){ //если нужно показывать с последней страницы по умолчанию
$this->page = $this->last_page - 1;
$this->post['ecomment_page'] = $this->last_page;
} else {
$this->page = 0;
$this->post['ecomment_page'] = 1;
}
} else $this->page = $this->post['ecomment_page'] - 1;

//
$operation = 'op_'.($this->post['op'] ? $this->post['op'] : ($op ? $op : 'silent'));
if(!method_exists($this, $operation)){
$this->err[] = 'Указанная операция не существует';
$operation = 'op_init';
}
$this->$operation();

}

//волшебный метод wink.gif
//
function &__get($name){
if(property_exists(__CLASS__,$name)){
return $this->$name;
} else {
switch($name){

case 'ref':
$url = parse_url($_SERVER['HTTP_REFERER']);
if(!empty($this->post['ref'])){
$this->ref = $this->translit($this->post['ref']);
} else {
$this->ref = $url['path'];
}
if(!empty($this->query) && isset($url['query'])){ //добавляем в ref при любом раскладе параметр
parse_str($url['query'], $url['query']);
foreach(explode(',', $this->query) as $query){
$query = trim($query);
if(isset($url['query'][$query])) $this->ref.= '_'.$url['query'][$query];
}
}
$this->ref = $this->translit($this->ref);
return $this->ref;

case 'user_posted':
$this->user_posted = (!empty($this->post['ecomment_posted']) ? unserialize($this->post['ecomment_posted']) : array());
return $this->user_posted;

case 'user_rated':
$this->user_rated = (!empty($this->post['ecomment_rated']) ? unserialize($this->post['ecomment_rated']) : array());
return $this->user_rated;

case 'post':
case 'err':
case 'info':
$this->$name = array();
return $this->$name;

case 'is_admin':
if(!empty($_COOKIE['is_admin']) && $_COOKIE['is_admin'] == $this->salt_word($this->password.$_SERVER['SERVER_NAME'])){
$this->is_admin = true;
} else {
//$this->err[] = 'Вы не авторизированы.';
$this->is_admin = false;
}
return $this->is_admin;

case 'list':
$this->list = $this->get_comments($this->ref, true);
return $this->list;

case 'total':
$this->total = $this->get_total();
return $this->total;

case 'last_page':
if($this->is_admin){
$total = $this->total['total'] - $this->total['answers'];
} else {
$total = $this->total['moderated'] - $this->total['moderated_answers'];
}
$this->last_page = (int) ceil($total / $this->cpp);
return $this->last_page;

default:
$this->err[] = 'Обращение к незаданной переменной '.$name;
break;
}
}
}

//
// основные рабочие методы
//
//тихая инициализация
//
function op_silent(){
//ничего не делаем.
}

//инициализация гостевой или просто вывод списка комментов + форма
//
function op_init(){
header("Content-type: application/x-javascript");
exit('var data = '.json_encode(array(
'list'=>$this->render_list(),
'info'=>$this->render_info(),
'desktop'=>$this->render_form()
)).'; html_return(data);');
}

//получение списка комментариев (без обновления формы, экономим трафик)
//
function op_get_list(){
exit(json_encode(array(
'list'=>$this->render_list(),
'info'=>$this->render_info()
)));
}

//авторизация
//
function op_login(){
$list = '';
if($this->post['password'] == $this->password){
$_COOKIE['is_admin'] = $this->salt_word($this->password.$_SERVER['SERVER_NAME']);
setcookie('is_admin', $this->salt_word($this->password.$_SERVER['SERVER_NAME']), 0);
$this->is_admin = true;
$this->info[] = 'Вы успешно авторизированы.';
$list = $this->render_list();
} else {
$this->err[] = 'Неверный пароль администратора.';
}
exit(json_encode(array(
'list'=>$list,
'info'=>$this->render_info(),
'desktop'=>$this->render_form()
)));
}

//метод выхода (разлогинивание)
//
function op_logout(){
$list = '';
if(isset($_COOKIE['is_admin'])){
unset($_COOKIE['is_admin']);
$this->is_admin = false;
setcookie('is_admin', '', 0);
$list = $this->render_list();
$this->info[] = 'Вы успешно разлогинились.';
} else {
$this->err[] = 'Вы не были авторизованы.';
}
exit(json_encode(array(
'list'=>$list,
'info'=>$this->render_info(),
'desktop'=>$this->render_form()
)));
}

//добавление нового комментария
//
function op_add_comment(){
$comment = array(
'name'=>htmlspecialchars(trim($this->post['name'])),
'email'=>htmlspecialchars(trim($this->post['email'])),
'message'=>$this->post['message'],
'moderated'=>!$this->moderate,
'date' => time(),
'key' => $this->get_timeid(),
'rating' => 0,
'parent' => preg_replace('/[^\d\.]*/iu', '', $this->post['parent'])
);

//проверки на корректность ввода
if(!$comment['name']){
$this->err[] = 'Имя комментатора не должно быть пустым.';
}
if(!filter_var($comment['email'],FILTER_VALIDATE_EMAIL)){
$this->err[] = 'Введен некорректный электронный адрес.';
}
if(!$comment['message']){
$this->err[] = 'Необходимо ввести текст комментария.';
}
if($this->max_length && (mb_strlen($comment['message'], 'UTF-8') > $this->max_length)){
$this->err[] = 'Длинна комментария не должна превышать <b>'.$this->max_length.'</b> символов.';
} else $comment['message'] = nl2br(htmlspecialchars(trim($this->post['message'])));

if($this->post['e-mail']){
$this->err['spam'] = 'Вы не прошли бот-проверку.';
}
if(empty($this->post[$this->salt_word($this->ref.$this->post['ecomment_start'])])){
$this->err['spam'] = 'Вы не прошли бот-проверку. Попробуйте еще раз.';
}

//если не было ошибок, то сохраняем
if(!sizeof($this->err)){

//регистрируем ответ у родительского сообщения
if($comment['parent']){
if($parent = $this->get_comment($comment['parent'])){
$this->list[$parent['key']]['childs'][] = $comment['key'];
}
}
$this->list[$comment['key']] = $comment; //добавляем сам новый коммент
if($this->save_comments($this->ref, $this->list)){
$this->info[] = 'Ваш комментарий успешно добавлен.';
if($this->moderate) {
$this->info[] = 'Комментарий появится в общем списке сразу же после одобрения модератором.';
}
if($this->notify){
$this->comment_notify($comment);
}
$this->user_posted[] = $comment['key'];
setcookie('ecomment_posted', serialize($this->user_posted), 0x7FFFFFFF);
unset(
$this->post['message'],
$this->post['parent']
); //чистим то, что не должно больше запоминаться
}

} else {
$this->err[] = 'Сообщение не было сохранено. Заполните все поля корректно.';
}
exit(json_encode(array(
'list'=>$this->render_list(),
'info'=>$this->render_info(),
'desktop'=>$this->render_form()
)));
}

//удаление комментария
//
function op_delete_comment(){
$list = '';
if($this->is_admin){
if($comment = $this->get_comment($this->post['id'])){
if(!empty($comment['parent'])){ //вычищаем упоминание об удаляемом комменте у его родителя (если есть родитель)
if($parent = $this->get_comment($comment['parent'], false)){
unset($parent['childs'][array_search($comment['key'], $parent['childs'])]);
$this->list[$parent['key']] = $parent;
}
}
if(!empty($comment['childs'])){ //вычищаем у дочерних ответов инфу о родителе (если есть дочерние)
foreach($comment['childs'] as $child){
$parent = ($comment['parent'] ? $comment['parent'] : '');
$this->list[$child]['parent'] = $parent; //переписываем все дочерние ответы родителю удаляемого ответа
if($this->get_comment($parent, false)){
$this->list[$parent]['childs'][] = $child;
}
}
}
unset($this->list[$comment['key']]);
if($this->save_data($this->ref, $this->list)){
$this->info[] = 'Комментарий успешно удален.';
$list = $this->render_list();
}
}
}
exit(json_encode(array(
'list'=>$list,
'info'=>$this->render_info()
)));
}

//toggle статуса промодерированности комментария
//
function op_moderate_comment(){
$list = '';
if($this->is_admin){
if(isset($this->list[$this->post['id']])){
$this->list[$this->post['id']]['moderated'] = !$this->list[$this->post['id']]['moderated'];
if($this->save_data($this->ref, $this->list)){
$this->info[] = 'Комментарий успешно промодерирован.';
$list = $this->render_list();
}
}
}
exit(json_encode(array(
'list'=>$list,
'info'=>$this->render_info()
)));
}

//повышение рейтинга комментария
//
function op_rate_up(){
$list = '';

if(isset($this->list[$this->post['id']])){
if($this->can_rate($this->post['id'], true)){
$comment = $this->list[$this->post['id']];
$comment['rating'] = ($comment['rating'] ? $comment['rating']+1 : 1);
$this->list[$this->post['id']] = $comment;
$this->user_rated[] = $comment['key'];
$this->user_rated = array_unique($this->user_rated);
if($this->save_data($this->ref, $this->list)){
setcookie('ecomment_rated', serialize($this->user_rated), 0x7FFFFFFF);
$list = $this->render_list();
}
}
}

exit(json_encode(array(
'list'=>$list,
'info'=>$this->render_info()
)));
}

//понижение рейтинга комментария
//
function op_rate_down(){
$list = '';

if(isset($this->list[$this->post['id']])){
if($this->can_rate($this->post['id'], true)){
$comment = $this->list[$this->post['id']];
$comment['rating'] = ($comment['rating'] ? $comment['rating']-1 : -1);
$this->list[$this->post['id']] = $comment;
$this->user_rated[] = $comment['key'];
$this->user_rated = array_unique($this->user_rated);
if($this->save_data($this->ref, $this->list)){
setcookie('gb_rated', serialize($this->user_rated), 0x7FFFFFFF);
$list = $this->render_list();
}
}
}

exit(json_encode(array(
'list'=>$list,
'info'=>$this->render_info()
)));
}

//получение информации о списке комментов (количество комментов)
//
function get_total($ref = ''){
if(!$ref) $ref = $this->ref;
//$this->list = $this->get_comments($ref, true, 'Получение списка для подсчета комментариев.');
$this->list = $this->get_comments($ref);
$total = array(
'ref' => $ref,
'total'=>sizeof($this->list),
'moderated'=>0,
'answers'=>0,
'moderated_answers'=>0
);
foreach($this->list as $comment){
if($comment['moderated']) $total['moderated']++;
if($comment['parent']) $total['answers']++;
if($comment['parent'] && $comment['moderated']) $total['moderated_answers']++;
}
return $total;
}

//получение информации о списке комментов (количество комментов)
//
function op_get_total($ref = ''){
exit(json_encode($this->get_total($ref)));
}

//
// методы рендера
//

//рендер пагинации
//принимает значения: количество элементов всего, текущая страница, элементов на страницу, строка GET или массив параметров для ссылки на страницу
//страница - принимаем системное значение (счет от нуля), а возвращаем - пользовательское (от 1)
function render_pagination($count = 1, $current = 0, $cpp = 1, $options = ''){
if(!$count || $count<=$cpp){
return '';
}
if(is_array($options)){
$tmp = '';
foreach($options as $key=>$val){
$tmp.= '&'.$key.'='.$val;
}
$options = $tmp;
}

$first = $prev = $next = $last = false;
$page_count = ceil($count / $cpp);
//начальная точка
$start = $current - 3;
if($start >= 1) { $prev = true; $first = true; }
if($start < 1) $start = 0;
//конечная точка
$end = $current + 3;
if($end < ($page_count-1)) { $next = true; $last = true; }
if($end >= $page_count) $end = $page_count-1;

$echo = '<div class="pagination"><small>Страницы'.(($page_count>11)?' (всего '.$page_count.')':'').':</small><br />';
if($first) $echo.= '<a href="?ecomment_page=1'.$options.'" class="first">первая</a>';
if($prev) $echo.= '<a href="?ecomment_page='.$current.$options.'" class="prev">&laquo;</a> ... ';

for($i = $start; $i <= $end; $i++){
$echo.= '<a href="?ecomment_page='.($i+1).$options.'" '.(($i==$current)?'class="active"':'').'>'.($i+1).'</a>';
}

if($next) $echo.= ' ... <a href="?ecomment_page='.($current+2).$options.'" class="next">&raquo;</a>';
if($last) $echo.= '<a href="?ecomment_page='.$page_count.$options.'" class="last">последняя</a>';

$echo.= '</div>';
return $echo;
}

//рендер списка комментариев (основная логика)
//
function render_list($ref = false, $log = true){
$echo = '<a name="ecomment_list"></a>'; //оставляем пробел, чтобы список не был пустым

if($ref) $this->list = $this->get_comments($ref, $log);
$list = $this->list;

ksort($list); //сортировка по ключам, что дает историческую сортировку

if($this->total_reverse) $list = array_reverse($list, true); //историческая сортировка - старые сообщения на последних страницах

if(!$list) return ' ';

//фильтруем, оставляя только исходные комментарии (без ответов) в любом случае, чтобы не дублировались
foreach($list as $comment){
if($comment['parent'] && $this->get_comment($comment['parent']))
unset($list[$comment['key']]);
}

//фильтруем, если есть необходимость, от не прошедших модерацию комментов
if(!$this->is_admin && $this->moderate){
$filtered = array();
foreach($list as $key => $comment)
if(!$comment['moderated']) unset($list[$key]);
}

//включаем пагинацию
$count = sizeof($list);
$options = array('op' => 'get_list');
if($this->pagination_top) $echo.= $this->render_pagination($count, $this->page, $this->cpp, $options); //верхняя пагинация


//обрезаем лишние сообщения
$list = array_slice($list, $this->page*$this->cpp, $this->cpp);

//реверс сообщений на странице - свержие вверху (двойное отрицание ибо один реверс уже был)
if($this->page_reverse) $list = array_reverse($list, true);

//перебор списка с комментариями
foreach($list as $comment){
if($this->is_admin || $comment['moderated'] || !$this->moderate)
$echo.= $this->render_comment($comment, $log);
}
if($this->pagination_bottom) $echo.= $this->render_pagination($count, $this->page, $this->cpp, $options); //нижняя пагинация
return $echo;
}

//Рендер одного конкретного комментария
//
function render_comment($comment, $log = true){
$control = '';
if($this->is_admin){
$control = '<div class="ecomment_control">
<a href="?op=moderate_comment&id='.$comment['key'].($this->post['ecomment_page'] ? '&ecomment_page='.$this->post['ecomment_page'] : '').'" class="ecomment_op">'.($comment['moderated'] ? 'скрыть' : 'утвердить').'</a>
&nbsp;|&nbsp;
<a href="?op=delete_comment&id='.$comment['key'].($this->post['ecomment_page'] ? '&ecomment_page='.$this->post['ecomment_page'] : '').'" class="ecomment_op">удалить</a>
</div>';
}
$rating = '';
if($this->rating){
$rating = '
<div class="ecomment_comment_rating">
<a href="?op=rate_up&id='.$comment['key'].($this->post['ecomment_page'] ? '&ecomment_page='.$this->post['ecomment_page'] : '').'" title="Повысить рейтинг" class="ecomment_rate_up ecomment_op">+</a>
<span class="ecomment_rating_value'.($comment['rating'] < 0 ? ' negative': '').'" title="Рейтинг сообщения"> '.$comment['rating'].' </span>
<a href="?op=rate_down&id='.$comment['key'].($this->post['ecomment_page'] ? '&ecomment_page='.$this->post['ecomment_page'] : '').'" title="Понизить рейтинг" class="ecomment_rate_down ecomment_op">-</a>
</div>';
}
$answer = '';
if($this->answer_allowed ){
if(!$this->answer_only_top || ($this->answer_only_top && empty($comment['parent'])))
$answer = '<small class="ecomment_answer_title">(<a href="?id='.$comment['key'].'" class="ecomment_answer_link">ответить</a>)</small>';
}
$echo = '
<div class="ecomment '.($comment['moderated'] ? 'moderated' : 'unmoderated').'">
<div class="ecomment_avatar"><img src="http://www.gravatar.com/avatar/'.md5(strtolower(trim($comment['email']))).'?s='.$this->gravatar_size.'&d='.urlencode($this->gravatar_default).'"/></div>
<div class="ecomment_date">'.date('d.m.Y', $comment['date']).'</div>
'.$rating.'
<div class="ecomment_name">
'.$comment['name'].$answer.'
</div>
<div class="ecomment_message">'.$comment['message'].'</div>'.$control.'
</div>
';
if(!empty($comment['childs'])){
$echo.= '<div class="ecomment_answers">';
foreach($comment['childs'] as $key){
if($child = $this->get_comment($key, true)){
if($this->is_admin || $child['moderated'] || !$this->moderate){
$echo.= $this->render_comment($child , $log );
}
}
}
$echo.= '</div>';
}
return $echo;
}

//рендер информационных сообщений
//
function render_info(){
$err = $info = '';
if($this->err) $err = '<div class="ecomment_err">'.implode('<br />', $this->err).'</div>';
if($this->info) $info = '<div class="ecomment_info">'.implode('<br />', $this->info).'</div>';
return $err.$info;
}

//Рендер формы
//
function render_form(){
$start = $this->get_timeid();
//избавляемся от error Notice
$this->post['parent'] = (empty($this->post['parent']) ? '' : $this->post['parent']);
$this->post['name'] = (empty($this->post['name']) ? '' : $this->post['name']);
$this->post['email'] = (empty($this->post['email']) ? '' : $this->post['email']);
$this->post['message'] = (empty($this->post['message']) ? '' : $this->post['message']);

return '
<h3></h3>
<form method="post" class="ecomment_form">
<input type="hidden" name="op" value="add_comment"/>
<input type="hidden" name="ecomment_start" value="'.$start.'"/>
<input type="hidden" name="ecomment_page" value="'.$this->post['ecomment_page'].'"/>
<input type="hidden" name="parent" value="'.$this->post['parent'].'"/>
<div class="ecomment_form_login">'.($this->is_admin ? '<a href="?op=logout" class="ecomment_op">logout</a>' : '<a href="?op=login" class="ecomment_op">login</a>').'</div>
<dl>
<dt>Имя:</dt>
<dd><input type="text" name="name" class="ecomment_form_name" value="'.htmlspecialchars($this->post['name']).'"/><span class="ecomment_answer_caption"></span></dd>

<dt>Email:</dt>
<dd>
<input type="email" name="email" class="ecomment_form_email" value="'.htmlspecialchars($this->post['email']).'"/>
<input type="text" name="e-mail" value=""/>
</dd>

<dt>Отзыв:</dt>
<dd>
<textarea name="message" class="ecomment_form_message" maxlength="'.$this->max_length.'">'.$this->post['message'].'</textarea>

</dd>

<dt>&nbsp;</dt>
<dd>
<input type="submit" class="ecomment_form_submit" value="Добавить отзыв"/>

</dd>
</dl>
</form>
<script language="JavaScript" type="text/javascript">
$(".ecomment_form_message").after(\'<br /><input type="checkbox" name="'.$this->salt_word($this->ref.$start).'" class="ecomment_form_not_robot" value="test"/> - все верно\');
var ecomment_counter = '.$this->max_length.'
</script>
';
}


//
// методы ЧТЕНИЯ и СОХРАНЕНИЯ в файловой системе
//

//чтение списка комментариев
//
private function get_comments($ref, $log = true, $info = ''){
$ref = $this->translit($ref);
if($list = $this->read_data($ref, false)){
return $list;
} else {
if($log) $this->info[] = 'Для текущей страницы нет комментариев. '.$info;
return array();
}
}

//выбор определенного коммента из текущего списка
//
private function get_comment($key, $log = true){
if(isset($this->list[$key])){
return $this->list[$key];
} else {
if($log) $this->err[] = 'В текущем списке нет указанного комментария "'.$key.'".';
return false;
}
}

//сохранение комментария
//
private function save_comment($ref, $comment, $log = true){
if(!$list = $this->read_data($ref, false)){
$list = array();
}
$list[$comment['key']] = $comment;
return $this->save_data($ref, $list, $log);
}

//сохранение комментариев (всего списка)
//
private function save_comments($ref, $list, $log = true){
return $this->save_data($ref, $list, $log);
}


//чтение .dat-файлов с сериалиализованными данными
//
private function read_data($name, $log = true){
if(@$data = file_get_contents(STORE.$name.'.dat')){
$data = unserialize($data);
if($data !== false){
return $data;
} else {
if($log) $this->err[] = 'Не удалось распаковать данные из файла.';
return false;
}
} else {
if($log) $this->err[] = 'Не удалось прочесть файл данных "'.$name.'".';
return false;
}
}

//сохранение сериализованных данных
//
private function save_data($name, $data, $log = true){
if(@file_put_contents(STORE.$name.'.dat', serialize($data))){
return true;
} else {
if($log) $this->err[] = 'Не удалось сохранить файл данных с комментариями.';
if(file_exists(STORE)){
if(!is_writable(STORE)) if($log) $this->err[] = 'Недостаточно прав доступа к директрории хранения данных.';
} elseif($log) $this->err[] = 'Указанная директория хранения файлов не существует.';

return false;
}
}

//
// Вспомогательные методы
//

//"соленое слово"
//
function salt_word($word){
return md5(md5($this->salt).md5($word));
}

//метка времени в качестве uid - с микросекундами, но без ведущих 2х цифр
//
protected function get_timeid(){
$time = microtime(true);
$time = $time*100; //избавились от дробной части
return substr($time, 0, 12);
}

//Транслитерация
//
function translit($str){
$rp = array("Ґ"=>"G","Ё"=>"YO","Є"=>"Ye&quo t;,"є"=>"ie","Ї"=>"YI","І"=>"I",
"і"=>"i","ґ"=>"g","ё"=>"yo",&quo t;№"=>"#","є"=>"e",
"ї"=>"yi","А"=>"A","Б"=>"B",&quo t;В"=>"V","Г"=>"G",
"Д"=>"D","Е"=>"E","Ж"=>"ZH",&quo t;З"=>"Z","И"=>"I",
"Й"=>"Y","К"=>"K","Л"=>"L"," ;М"=>"M","Н"=>"N",
"О"=>"O","П"=>"P","Р"=>"R"," ;С"=>"S","Т"=>"T",
"У"=>"U","Ф"=>"F","Х"=>"H"," ;Ц"=>"Ts","Ч"=>"Ch",
"Ш"=>"Sh","Щ"=>"Shch","Ъ"=>"'&quo t;,"Ы"=>"Yi","Ь"=>"",
"Э"=>"E","Ю"=>"Yu","Я"=>"Ya",&qu ot;а"=>"a","б"=>"b",
"в"=>"v","г"=>"g","д"=>"d"," ;е"=>"e","ж"=>"zh",
"з"=>"z","и"=>"i","й"=>"y"," ;к"=>"k","л"=>"l",
"м"=>"m","н"=>"n","о"=>"o"," ;п"=>"p","р"=>"r",
"с"=>"s","т"=>"t","у"=>"u"," ;ф"=>"f","х"=>"h",
"ц"=>"ts","ч"=>"ch","ш"=>"sh",&q uot;щ"=>"shch","ъ"=>"'",
"ы"=>"yi","ь"=>"","э"=>"e"," ;ю"=>"yu","я"=>"ya",
" "=>"_","»"=>"","«"=>""
);
$str = strtr($str, $rp);
return preg_replace('/[^-\d\w]/','',$str);
}

//уведомление о новом комментарии
//
protected function comment_notify($comment = false){

//составляем заголовки
$mailHeaders = "Date: ".date("D, d M Y H:i:s")." UT\r\n";
$mailHeaders.= "Subject: =?UTF-8?B?".base64_encode($this->mail_subject)."?=\r\n";
$mailHeaders.= "MIME-Version: 1.0\r\n";
$mailHeaders.= "Content-Type: text/html; charset=\"UTF-8\"\r\n";
$mailHeaders.= "Content-Transfer-Encoding: 8bit\r\n";
$mailHeaders.= "From: =?UTF-8?B?".base64_encode($this->mail_sender_name)."?= <".$this->mail_target.">\r\n";
$mailHeaders.= "X-Priority: 3";
$mailHeaders.= "X-Mailer: PHP/".phpversion()."\r\n";

$mailBody = 'На странице <a href="'.$_SERVER['HTTP_REFERER'].'?ecomment_page='.$this->post['ecomment_page'].'#ecomment_list">'.$_SERVER['HTTP_REFERER'].'</a> оставлен новый комментарий:<br /><br />';
if($comment){
$mailBody.= '<b>Автор:</b> '.$comment['name'].'<br />';
$mailBody.= '<b>Email:</b> '.$comment['email'].'<br />';
$mailBody.= '<b>Сообщение:</b> '.$comment['message'].'<br />';
}
$result = 1;
foreach(explode(',', $this->mail_target) as $mail){
$result*= mail(trim($mail), $this->mail_subject, $mailBody, $mailHeaders);
}
return $result;
}

//проверка не разрешение юзеру оценивать посты
//
protected function can_rate($key = '', $log = false){
if(!$this->is_admin){
if(!in_array($key, $this->user_posted)){ //запрещаем рейтить свои же посты
if(!in_array($key, $this->user_rated)){ //запрещаем рейтить уже оцененные посты
if($this->moderate){ //если включена премодерация сообщений, то проверяем доверенность пользователя
foreach($this->user_posted as $posted){
if(isset($this->list[$posted]) && $this->list[$posted]['moderated']){
return true;
}
}
if($log) $this->err[] = 'Оценивать сообщения могут лишь пользователи, оставившие в теме обсуждения хотя бы один одобренный модератором комментарий.';
} else return true;
} elseif($log) $this->err[] = 'Вы уже оценивали этот пост.';
} elseif($log) $this->err[] = 'Авторы не могут оценивать собственные сообщения.';
} else return true;
return false;
}

}
if($_REQUEST['op']){
$ecomment = new ecomment($_REQUEST['op']);
}
?>[code]
Быстрый ответ:

 Графические смайлики |  Показывать подпись
Здесь расположена полная версия этой страницы.
Invision Power Board © 2001-2024 Invision Power Services, Inc.