use Storable qw(freeze thaw);
use Date::Parse;
use Email::Valid;
+use Image::Size;
+use HTML::BBReverse;
+use POSIX;
use LWP::UserAgent;
use Net::OpenID::Consumer;
#
profile => "normal",
setrights => "admin",
);
-
+our $path_translated; # Untainted value of PATH_TRANSLATED env var
my $cgi = new CGI;
print STDERR "--------------------\n";
my $forum=get_forum_config();
-
authorize_user($cgi,$forum);
if ($cgi->request_method ne "POST") {
# Запрос к скрипту методом GET. Надо показать форму, если только это не
# нехороших символов нет, но чтобы perl в taint mode не
# ругался...
if (allow_operation($param,$cgi,$forum)) {
+ print STDERR "Allow_operation completed\n";
show_template($1,$cgi,$forum) if $param=~/^(\w+)$/;
exit;
} else {
return $prefix.substr($dir,length($root));
}
#
-# Поиск файла .forum вверх по дереву от $ENV{PATH_TRANSLATED}
+# Поиск файла .forum вверх по дереву от $path_translated
# Значение PATH_TRANSLATED считаем безопасным - наш web-сервер нам не
# враг.
# Возвращает список имя,значение, имя, значение который прививается в
# хэш
sub get_forum_config {
- my @path=split("/",$1) if $ENV{PATH_TRANSLATED}=~/^(\S+)$/;
+ $path_translated = $1 if $ENV{PATH_TRANSLATED}=~/^(\S+)$/;
+ $path_translated=~s/\/+$//;
+ my @path=split("/",$path_translated);
while (@path>1) {
if (-r (my $config=join("/",@path,".forum")) ) {
open F,"<",$config;
}
$config{"userurl"} = dir2url($cgi,$config{"userdir"});
-
#
# Если нет ссылки в конфиге на файл паролей или он не
# существует, выдаем ошибку. С офоромлением, так как шаблоны
$config{"authperiod"}="+1M" if (! exists $config{"authperiod"});
$config{"renewtime"} = "86000" if (!exists $config{"renewtime"});
$config{"replies_per_page"} = 50 if (!exists $config{"replies_per_page"});
+ $config{"indexfile"} = "index.html" if (!exists $config{"indexfile"});
return \%config;
}
pop @path;
exit;
}
-sub gettemplate {
- my ($forum, $template,$url) = @_;
- my $filename=$forum->{"templates"}."/$template.html";
- if (! -r $filename) {
- show_error($forum,"Нет шаблона $template");
- exit;
- }
- my $tree = HTML::TreeBuilder->new_from_file($filename);
- fix_forum_links($forum,$tree,$url);
- return $tree;
-}
#
# Вывод шаблона формы. В шаблоне должна присутстовать форма с
# именем, совпадающим с именем form. Если в $cgi есть параметры, имена
} else {
$element->attr("value",$cgi->param($name));
}
- } elsif ($f->tag eq "textarea") {
- $f->delete_content;
- $f->push_content($cgi->param("name"));
- } elsif ($f->tag eq "select") {
- for my $option ($f->find_by_tag_name("option")) {
- if (grep($option->attr("value") eq $_, $cgi-param("name"))) {
+ } elsif ($element->tag eq "textarea") {
+ $element->delete_content;
+ $element->push_content($cgi->param($name));
+ } elsif ($element->tag eq "select") {
+ for my $option ($element->find_by_tag_name("option")) {
+ if (grep($option->attr("value") eq $_, $cgi->param($name))) {
$option->attr("selected","");
} else {
$option->attr("selected",undef);
}
}
- $f->attr("type","POST");
+ $f->attr("method","POST");
for my $required ($form,"returnto") {
if (!$substituted{$required}) {
my $element = new HTML::Element('input',
#
sub fix_forum_links {
my ($forum,$tree,$path_info) = @_;
- $path_info=$ENV{'PATH_INFO'} if (!defined $path_info);
+ if (!defined $path_info) {
+ $path_info = $ENV{PATH_INFO};
+ $path_info =~ s/\/+/\//g;
+ }
my $script_with_path = $ENV{SCRIPT_NAME}.$path_info;
ELEMENT:
for my $element ($tree->find_by_tag_name("form","img","link","script","a")) {
}
my $link = $element->attr($attr);
# Абсолютная ссылка - оставляем как есть.
- next ELEMENT if (! defined $link || $link=~/^\w+:/);
+ next ELEMENT if (! defined $link || $link=~/^\w+:/ || $link
+ eq"."||$link eq "..");
# Ссылка от корня сайта.
if (substr($link,0,1) eq "/") {
# Если она не ведет на наш скрипт, не обрабатываем
sub substitute_user_info {
-my ($tree,$forum) = @_;
-my %userinfo = %{$forum->{"authenticated"}};
+my ($tree,$forum,$user) = @_;
+my %userinfo;
+if (defined $user) {
+ my %users;
+ dbmopen %users,datafile($forum,"passwd"),0644;
+ if (!$users{$user}) {
+ show_error($forum,"Неизвестный пользователь $user");
+ }
+ my $record = thaw($users{$user});
+ %userinfo = %$record;
+ $userinfo{"user"} = $user;
+} else {
+ # Если не сказано, какой юзер, то текущий.
+ %userinfo = %{$forum->{"authenticated"}}
+}
#
# Специально обрабатываем поля user (должна быть ссылка) и avatar
# (должен быть img).
-my @userlink = $tree->look_down("_tag"=>"a","class"=>"author");
-if (@userlink) {
my $userpage;
- if ($userinfo{"user"}=~/^http:/) {
- $userpage = $userinfo{"user"};
+ if ($userinfo{"openiduser"}) {
+ $userpage = "http://".$userinfo{"user"};
} else {
$userpage =
$cgi->url(-absolute=>1).$forum->{"userurl"}."/".$cgi->escape($userinfo{"user"});
}
- for my $element (@userlink) {
- $element->attr(href=>$userpage);
- $element->delete_content();
- $element->push_content($userinfo{"user"});
- }
-}
-delete $userinfo{"userpage"};
-delete $userinfo{"user"};
-my $avatar = $tree->look_down("_tag"=>"img","class"=>"avatar");
-if ($avatar) {
- $avatar->attr(src=>$userinfo{"avatar"});
-}
-delete $userinfo{"avatar"};
+ substinfo($tree,["_tag"=>"a","class"=>"author"],
+ href=>$userpage,_content=>$userinfo{"user"});
+ delete $userinfo{"user"};
+ if (ref $userinfo{"avatar"} eq "HASH") {
+ substinfo($tree,["_tag"=>"img","class"=>"avatar"],
+ %{$userinfo{'avatar'}});
+ } elsif ($userinfo{'avatar'}) {
+ substinfo($tree,["_tag"=>"img","class"=>"avatar"],
+ src=>$userinfo{"avatar"});
+ } else {
+ substinfo($tree,["_tag"=>"img","class"=>"avatar"],
+ src=>$forum->{templatesurl}."/1x1.gif",
+ width=>1,height=>1);
+ }
+ delete $userinfo{"avatar"};
-while (my ($field,$value)=each %userinfo) {
- my $element = $tree->look_down("class","a".$field);
- if ($element) {
- $element->delete_content();
- #
- # FixME - allow HTML in author attributes
- $element->push_content($value);
+ for my $element ( $tree->look_down("class",qr/^ap-/)) {
+ my $field=$1 if $element->attr("class")=~/^ap-(.*)$/;
+ $element->delete_content();
+ $element->push_content(str2tree($userinfo{$field}))
+ if $userinfo{$field};
+ $element->attr(href=>"mailto:$userinfo{$field}")
+ if ($element->tag eq "a" && $field eq "email");
}
-}
}
#
}
print STDERR "user $user restored session $session\n";
$forum->{"authenticated"}=$userinfo;
- print STDERR "authorize_user:
- ",$forum->{authenticated}{user},
+ print STDERR "authorize_user: ",$forum->{authenticated}{user},
$forum->{authenticated},"\n";
}
dbmclose %userbase;
newsession(undef,$forum,$user);
forum_redirect($cgi,$forum,$returnto)
}
+sub clear_user_cookies {
+ my ($cgi,$forum) = @_;
+ $forum->{cookies}=[ $cgi->cookie(-name=>"sluser", -value=>"0",
+ -expires=>"-1m"),$cgi->cookie(-name=>"slsession", -value=>"0",
+ -expires => "-1m")];
+}
#
# Обработчик формы логина. Сводится к вызову функции authenticate,
# поскольку мы поддерживаем логин одновременный с отправкой реплики.
show_template(@_);
}
}
-sub clear_user_cookies {
- my ($cgi,$forum) = @_;
- $forum->{cookies}=[ $cgi->cookie(-name=>"sluser", -value=>"0",
- -expires=>"-1m"),$cgi->cookie(-name=>"slsession", -value=>"0",
- -expires => "-1m")];
-}
#
# Обработчик формы logout. В отличие от большинства обработчиков форм,
# поддерживает обработку методом GET
#
# Находим файл дискуссии, в который надо поместить реплику
#
+ my ($tree,$lockfd)=gettree($path_translated);
+ my $newmsg = newlistelement($tree,"message","messagelist");
+ if (!$newmsg) {
+ show_error($forum,"Шаблон темы не содержит элемента с классом
+ message");
+ exit;
+ }
+ #
+ # Генерируем идентификатор записи.
#
- # Сохраняем приаттаченную картинку, если есть.
+ my $id = get_uid($forum);
+
+
#
-
- # Генерируем идентификатор записи.
+ # Сохраняем приаттаченные картинки, если есть.
#
-
+ my $dir = $path_translated;
+
+ $dir=~ s/[^\/]+$// if (-f $dir);
+ my %attached;
+ for (my $i=1;$cgi->param("image$i"); $i++) {
+ my $userpath=$cgi->param("image$i");
+ my $filename=lc($1) if $userpath =~ /([^\/\\]+)$/;
+ $attached{$filename} = $id."_".$filename;
+ my $in = $cgi->upload("image$i");
+ if (!$in) {
+ show_error($forum,"Ошибка при загрузке картинки $filename");
+ exit;
+ }
+ my $out;
+ open $out,">$dir/$attached{$filename}";
+ binmode $out,":bytes";
+ local $/=undef;
+ my $data = <$in>;
+ print $out $data;
+ close $in;
+ close $out;
+ }
#
# Преобразуем текст записи в html и чистим его
#
- my $txtree = undef;
- if ($cgi->param("format") eq "bbcode") {
-
- } elsif ($cgi->param("format") eq "text") {
- my $text = $cgi->escapeHTML($cgi->param("text"));
- $text=~s/\r?\n\r?\n/<p>/;
- $text=~s/\n/<br>/;
- $txtree =
- HTML::TreeBuilder->new_from_content("<div>$text</div>");
- } else { # Default - html
- $txtree =
- HTML::TreeBuilder->new_from_content("<div>".$cgi->param("text")."</div>");
- for my $badtag
- ("script","style","head","html","object","embed","iframe","frameset","frame",
- ($forum->{forbid_tags}?split(/\s*,\s*/,$forum->{forbid_tags}):())) {
- for my $element ($txtree->find_by_tag_name($badtag)) {
- $element->delete() if defined $element;
- }
+ my $txtree = input2tree($cgi,$forum,"text");
+ #
+ # Находим в тексте URL на приаттаченные картинки и меняем на те
+ # имена, под которыми мы их сохранили.
+ #
+ for my $image ($txtree->find_by_tag_name("img")) {
+ my $file=lc($image->attr("src"));
+ if ( exists $attached{$file}) {
+ $image->attr("src" => $attached{$file});
+ my ($width,$height) = imgsize($dir ."/".$attached{$file});
+ $image->attr("width" =>$width);
+ $image->attr("height" => $height);
}
}
+ #
+ # Подставляем данные сообщения
+ #
+ $newmsg->attr("id"=>$id);
+ substinfo($newmsg,[class=>"subject"],_content=>$cgi->param("subject"));
+ my $textnode=$newmsg->look_down("class"=>"mtext");
+ if (!$textnode) {
+ show_error($forum,"В шаблоне реплики нет места для текста");
+ }
+ $textnode->delete_content();
+ $textnode->push_content($txtree);
+ if ($forum->{authenticated}{signature}) {
+ $textnode->push_content(new HTML::Element("br"),"--",
+ new HTML::Element("br"),str2tree($forum->{authenticated}{signature}));
+ }
+ substitute_user_info($newmsg,$forum);
+ #
+ # Подставляем данные в форму msginfo
+ #
+ my $editform=$newmsg->look_down(_tag=>"form","class"=>"msginfo");
+ if ($editform) {
+ substinfo($editform,[_tag=>"input",name=>"id"],value=>$id) ||
+ show_error($forum,"В форме управления сообщением нет поля id");
+ substinfo($editform,[_tag=>"input",name=>"author"],value=>
+ $forum->{authenticated}{user}) ||
+ show_error($forum,"В форме управления сообщением нет поля author");
+ }
+ # Подставляем mdate
+ substinfo($newmsg,["class"=>"mdate"],
+ _content =>strftime("%d.%m.%Y %H:%M",localtime()));
+ # Подставляем mreply
+ substinfo($newmsg,[_tag=>"a","class"=>"mreply"],"href" =>
+ $cgi->url(-absolute=>1,-path_info=>1)."?reply=1&id=$id");
+ # Подставляем manchor
+ substinfo($newmsg,[_tag=>"a","class"=>"manchor"],
+ "name"=>"#$id","href"=>undef) or
+ show_error($forum,"В шаблоне сообщения отсутствует якорь для ссылок на него");
+ # подставляем mlink
+ substinfo($newmsg,[_tag=>"a","class"=>"mlink"],
+ href=>$cgi->path_info."#id");
+ # подставляем mparent
+ my $parent_id=$cgi->param("id");
+ if ($parent_id) {
+ substinfo($newmsg,[_tag => "a",class=>"mparent"],
+ "href"=>$cgi->path_info."#$parent_id",style=>undef);
+ } else {
+ substinfo($newmsg,[_tag => "a",class=>"mparent"],
+ style=>"display: none;");
+ }
+
+ #
+ # Делаем Уфф и сохраняем то, что получилось
+ #
+ savetree($path_translated,$tree,$lockfd);
+ record_statistics($forum,"message"),
+ forum_redirect($cgi,$forum);
+
}
#
+# Обработка операции создания новой темы.
+#
+
+sub new_topic {
+ my ($form,$cgi,$forum) = @_;
+ #
+ # Проверяем корректность urlname и прочих полей
+ #
+ my $urlname;
+ if (!$cgi->param("urlname")) {
+ $urlname = get_uid($forum);
+ } else {
+ $urlname=$1 if $cgi->param("urlname") =~ /^([-\w]+)$/;
+ form_error($form,$cgi,$forum,"Некорректные символы в urlname.
+ Допустимы только латинские буквы, цифры и минус") unless $urlname;
+ }
+ if (!-d $path_translated) {
+ show_error($forum,"Операция $form может быть вызвана только со
+ страницы форума");
+ }
+ my $filename = "$path_translated/$urlname.html";
+ if (-f $filename) {
+ form_error($form,$cgi,$forum,"Тема с urlname $urlname уже
+ существует");
+ }
+ my $url = $cgi->url(-absolute=>1,-path_info=>1)."/$urlname.html";
+ $url =~ s/\/+/\//g;
+ if (!$cgi->param("title")) {
+ form_error($form,$cgi,$forum,"Тема должна иметь непустое название");
+ }
+ #
+ # Создаем собственно тему
+ #
+ my $tree = gettemplate($forum,"topic",$url);
+ # Заполнить название и аннотацию
+ my $abstract = input2tree($cgi,$forum,"abstract");
+ substinfo($tree,[_tag=>"meta","name"=>"description"],content=>$abstract->as_trimmed_text);
+ substinfo($tree,[_tag=>"title"],_content=>$cgi->param("title"));
+ my $subtree = $tree->look_down("class"=>"topic");
+ my $creation_time=strftime("%d.%m.%Y %H:%M",localtime());
+ if ($subtree) {
+ substinfo($subtree,["class"=>"title"],
+ _content=>$cgi->param("title"));
+ substinfo($subtree,["class"=>"date"],
+ _content=>$creation_time);
+ # Вставляем в страницу КОПИЮ аннотации, поскольку аннотация
+ # нам еще понадобится в списке тем.
+ substinfo($subtree,["class"=>"abstract"],_content=>$abstract->clone);
+ substitute_user_info($subtree,$forum);
+ } else {
+ substinfo($tree,["class"=>"title"],
+ _content=>$cgi->param("title"));
+ }
+ # Скрыть список сообщений.
+ hide_list($tree,"messagelist");
+ savetree($filename,$tree,undef);
+ $tree->destroy;
+ #
+ # Добавляем элемент в список тем текущего форума
+ #
+
+ my $lockfd;
+ ($tree,$lockfd)=gettree($path_translated."/".$forum->{"indexfile"});
+ my $newtopic = newlistelement($tree,"topic","topiclist");
+ substinfo($newtopic,[_tag=>"a","class"=>"title"],
+ _content=>$cgi->param("title"), href=>"$urlname.html");
+ substinfo($newtopic,["class"=>"date"], _content=>$creation_time);
+ substinfo($newtopic,["class"=>"abstract"],_content=>$abstract);
+ substitute_user_info($newtopic,$forum);
+ $newtopic->attr("id",$urlname);
+ my $controlform = $newtopic->look_down(_tag=>"form",class=>"topicinfo");
+ if ($controlform) {
+ $controlform->attr("action"=>$url);
+ substinfo($controlform,[_tag=>"input",name=>"author"],value=>
+ $forum->{authenticated}{user});
+ }
+ savetree($path_translated."/".$forum->{"indexfile"},$tree,$lockfd);
+ record_statistics($forum,"topic");
+ forum_redirect($cgi,$forum,$cgi->url(-base=>1).$url);
+}
+
+sub new_forum {
+ my ($form,$cgi,$forum) = @_;
+ #
+ # Проверяем корректность urlname и прочих полей
+ #
+ my $urlname;
+ if (!$cgi->param("urlname")) {
+ form_error($form,$cgi,$forum,"Форуму необходимо задать непустое urlname");
+ }
+ if ($cgi->param("urlname") eq ".") {
+ $urlname = "."
+ } else {
+ $urlname=$1 if $cgi->param("urlname") =~ /^([-\w]+)$/ ;
+ form_error($form,$cgi,$forum,"Некорректные символы в urlname.
+ Допустимы только латинские буквы, цифры и минус") unless $urlname;
+ }
+ if (!-d $path_translated) {
+ show_error($forum,"Операция $form может быть вызвана только со
+ страницы форума");
+ }
+ my $newname = "$path_translated/$urlname";
+ $newname=$path_translated if ($urlname eq ".");
+ my $filename = "$newname/$forum->{indexfile}";
+ if (-f $filename) {
+ form_error($form,$cgi,$forum,"Форум $urlname уже существует");
+ }
+ if (!$cgi->param("title")) {
+ form_error($form,$cgi,$forum,"Форум должен иметь непустое название");
+ }
+ mkdir $newname unless -d $newname;
+ #
+ # Сохраняем логотип
+ #
+ my ($logo_name,$logo_width,$logo_height);
+ if ($cgi->param("logo")) {
+ my $userpath = $cgi->param("logo");
+ $logo_name="logo.".lc($1) if $userpath=~/\.([^.]+)$/;
+ my $in = $cgi->upload("logo");
+ if (!$in) {
+ show_error($forum,"Ошибка при загрузке картинки $userpath");
+ exit;
+ }
+ my $out;
+ open $out,">$newname/$logo_name";
+ binmode $out,":bytes";
+ local $/=undef;
+ my $data = <$in>;
+ print $out $data;
+ close $in;
+ close $out;
+ ($logo_width,$logo_height) = imgsize("$newname/$logo_name");
+ } else {
+ $logo_name = $forum->{"templatesurl"}."/1x1.gif";
+ $logo_width = 1;
+ $logo_height=1;
+ }
+
+
+ #
+ # Создаем собственно оглавление форума
+ #
+
+ my $url = $cgi->path_info."/$urlname";
+ $url =~ s/\/+/\//g;
+ my $tree = gettemplate($forum,"forum",$url);
+ # Заполнить название и аннотацию
+ my $abstract = input2tree($cgi,$forum,"abstract");
+ substinfo($tree,[_tag=>"meta","name"=>"description"],content=>$abstract->as_trimmed_text);
+ substinfo($tree,[_tag=>"title"],_content=>$cgi->param("title"));
+ my $subtree = $tree->look_down("class"=>"annotation")
+ or show_error($forum,"В шаблоне форума отсутствует класс annotation");
+ my $creation_time=strftime("%d.%m.%Y %H:%M",localtime());
+ substinfo($subtree,["class"=>"title"],
+ _content=>$cgi->param("title"));
+ substinfo($subtree,["class"=>"date"],
+ _content=>$creation_time);
+ # Вставляем в страницу КОПИЮ аннотации, поскольку аннотация
+ # нам еще понадобится в списке тем.
+ substinfo($subtree,["class"=>"abstract"],_content=>$abstract->clone);
+ substitute_user_info($subtree,$forum);
+ substinfo($subtree,[_tag=>"img","class"=>"logo"],
+ src=> $logo_name, width=>$logo_width, height=>$logo_height);
+ # Скрыть списки подфорумов и тем .
+ hide_list($tree,"forumlist");
+ hide_list($tree,"topiclist");
+ if ($urlname eq ".") {
+ for my $link_up ($tree->look_down(_tag=>"a",href=>"..")) {
+ $link_up->delete;
+ }
+ }
+ savetree($filename,$tree,undef);
+ $tree->destroy;
+ #
+ # Добавляем элемент в список тем текущего форума
+ #
+ if ($urlname ne ".") {
+ my $lockfd;
+ ($tree,$lockfd)=gettree($path_translated."/".$forum->{"indexfile"});
+ my $newforum = newlistelement($tree,"forum","forumlist");
+ substinfo($newforum,[_tag=>"a","class"=>"title"],
+ _content=>$cgi->param("title"), href=>"$urlname/");
+ substinfo($newforum,["class"=>"date"], _content=>$creation_time);
+ substinfo($newforum,["class"=>"abstract"],_content=>$abstract);
+ substinfo($newforum,[_tag=>"img","class"=>"logo"],src=>"$urlname/$logo_name",
+ width=>$logo_width,height=>$logo_height);
+ substitute_user_info($newforum,$forum);
+ $newforum->attr("id",$urlname);
+ my $controlform = $newforum->look_down(_tag=>"form",class=>"foruminfo");
+ if ($controlform) {
+ $controlform->attr("action"=>$cgi->url(-absolute=>1,-path_info=>0).
+ $url);
+ substinfo($controlform,[_tag=>"input",name=>"author"],value=>
+ $forum->{authenticated}{user});
+ }
+ savetree($path_translated."/".$forum->{"indexfile"},$tree,$lockfd);
+ record_statistics($forum,"forum");
+ }
+ forum_redirect($cgi,$forum,$cgi->url(-base=>1).$url);
+}
+
+#----------------------------------------------------------
+# База пользователей и права доступа
+#----------------------------------------------------------
+#
+# Записывает в базу данных пользователей, сколько каких объектов
+# создал текущий пользователь
+#
+sub record_statistics {
+ my ($forum,$type) = @_;
+ my $user = $forum->{authenticated}{user};
+ my %base;
+ dbmopen %base,datafile($forum,"passwd"),0664;
+ my $userinfo = thaw($base{$user});
+ $userinfo->{$type."s"}++;
+ $userinfo->{"last_$type"}=time;
+ $base{$user} = freeze($userinfo);
+ dbmclose %base;
+}
+#
# читает файлы прав доступа в дереве форума, и возвращает
# статус текущего пользователя (undef - аноним, banned, normal,
# moderator или admin
return undef;
}
my $user = $forum->{authenticated}{user};
- my $dir = $ENV{'PATH_TRANSLATED'};
+ my $dir = $path_translated;
+ $dir =~s/\/$//;
$dir =~s/\/[^\/]+$// if (!-d $dir);
my $f;
my $user_status = "normal";
LEVEL:
while (length($dir)) {
+ print STDERR "Searcghing for perms in $dir\n";
if (-f "$dir/perms.txt") {
open $f,"<","$dir/perms.txt";
my $status = undef;
}
close $f;
last LEVEL if -f "$dir/.forum";
- # Strip last path component.
- $dir =~s/\/[^\/]+$//
}
+ # Strip last path component.
+ $dir =~s/\/[^\/]+$//
}
return $user_status;
}
+
+#------------------------------------------------------------------
+# Работа с файлами и идентификторами
+#------------------------------------------------------------------
+
#
# Залочить файл и получить его распрасенное представление.
# Возвращает пару ($tree,$lockfd)
my $f;
open $f,"<",$filename or return undef;
flock $f, LOCK_EX;
- my $tree = HTML::TreeBuider->new_from_file($f);
+ my $tree = HTML::TreeBuilder->new_from_file($f);
return ($tree,$f);
}
#
#
sub savetree {
- my ($filename,$tree,$lockfd) = shift;
+ my ($filename,$tree,$lockfd) = @_;
my $f;
open $f,">",$filename . ".new" or return undef;
print $f $tree->as_HTML("<>&");
rename $filename.".new",$filename;
close $lockfd if defined($lockfd);
}
+#
+# Читает шаблон и подготавливает его к размещению по указанной URL.
+# Если url не указана, считается что шаблон будет показан как результат
+# текущего http-запроса.
+sub gettemplate {
+ my ($forum, $template,$url) = @_;
+ $url =~ s/\/+/\//g;
+ my $filename=$forum->{"templates"}."/$template.html";
+ if (! -r $filename) {
+ show_error($forum,"Нет шаблона $template");
+ exit;
+ }
+ my $tree = HTML::TreeBuilder->new_from_file($filename);
+ fix_forum_links($forum,$tree,$url);
+ return $tree;
+}
#
sub get_uid {
my $forum = shift;
my $f;
- open $f,"<+",datafile($forum,"sequence");
+ open $f,"+<",datafile($forum,"sequence") or
flock $f,LOCK_EX;
my $id=<$f> || "0";
$id++;
seek $f,0,0;
printf $f "%8s\n",$id;
close $f;
- return sprintf ("%08s",$id);
+ $id=~/(\d+)/;
+ return sprintf ("%08s",$1);
}
-#
-# ----------------- OpenID registration -----------------------------
-#
+# --------------------------------------------------------------------
+# OpenID registration
+# -------------------------------------------------------------------
sub create_openid_consumer {
my ($cgi,$forum) = @_;
return Net::OpenID::Consumer ->new(
- ua => LWP::UserAgent->new(),
+ ua => LWP::UserAgent->new( agent => "Stilllife/1.0"),
args => $cgi,
consumer_secret=>"X9RWPo0rBE7yLja6VB3d",
required_root => $cgi->url(-base=>1));
my $username = $user;
$username =~ s/^http:\/\///;
if (!$userbase{$username}) {
- $userbase{$username} = freeze($forum->{authenticated}={"openiduser"=>1});
+ # Тащим foaf, если получится
+ my %info=get_foaf($csr->ua,$vident->declared_foaf);
+ if (ref($info{'avatar'}) eq "HASH" ) {
+ delete $info{'avatar'}{'type'};
+ }
+ $info{"openiduser"}=1;
+ $forum->{authenticated}=\%info;
+ $userbase{$username} = freeze(\%info);
} else {
$forum->{authenticated} = thaw ($userbase{$username});
}
exit;
}
}
+
+sub get_foaf {
+ my ($ua,$foaf_url) = @_;
+ my $response = $ua->get($foaf_url);
+ unless ($response->is_success) {
+ print STDERR "Error geting foaf from $foaf_url\n";
+ return ();
+ }
+ my $foaf = $response->content;
+ my %info = foaf_parse($foaf);
+ if ($info{avatar}) {
+ $response = $ua->get($info{avatar});
+ if ($response->is_success) {
+ my $image = $response->content;
+ my ($w,$h,$type) = imgsize(\$image);
+ $info{avatar}={width=>$w,height=>$h,type=>$type,src=>$info{avatar}};
+ } else {
+ print STDERR "Error getting $info{avatar}: ".$response->status_line,"\n";
+ }
+ }
+ return %info;
+}
+sub foaf_parse {
+ my $foaf = shift;
+ my ($starttag) = $foaf =~ /<(\w+(:\w+)?[^>]+)>/sg;
+ my %ns = reverse ($starttag =~ /xmlns:(\w+)="([^"]+)"/sg);
+ my $foaf_prefix = $ns{"http://xmlns.com/foaf/0.1/"};
+ my $rdf_prefix = $ns{"http://www.w3.org/1999/02/22-rdf-syntax-ns#"};
+ my ($userpic) = $foaf=~/<$foaf_prefix:img[^>]* $rdf_prefix:resource="([^"]+)"/s;
+ my @info;
+ push @info, avatar =>$userpic if $userpic;
+ my ($icq) = $foaf =~/<$foaf_prefix:icqChatID>([^<]*)<\/$foaf_prefix:icqChatID>/s;
+ push @info, icq => $icq if ($icq);
+ my ($jabber) = $foaf =~/<$foaf_prefix:jabberID>([^<]*)<\/$foaf_prefix:jabberID>/s;
+ push @info, jabber => $jabber if ($jabber);
+ return @info;
+}
+#-----------------------------------------------------------------
+# Обработка форматированных текстовых полей
+#-----------------------------------------------------------------
+
+sub input2tree {
+ my ($cgi,$forum,$field_name) = @_;
+ my $format = $cgi->param($field_name."_format");
+ my $text = $cgi->param($field_name);
+ if ($format eq "bbcode") {
+ my $parser = HTML::BBReverse->new();
+ $text="<div class=\"bbcode\">".$parser->parse($text)."</div>";
+ } elsif ($format eq "text") {
+ $text=~s/\r?\n\r?\n/<\/p><p class=\"text\">/;
+ $text=~s/\r?\n/<br>/;
+ $text = "<div><p class=\"text\">".$text."</p></div>";
+ }
+ my $txtree = str2tree($text);
+ for my $badtag
+ ("script","style","head","html","object","embed","iframe","frameset","frame",
+ ($forum->{forbid_tags}?split(/\s*,\s*/,$forum->{forbid_tags}):())) {
+ for my $element ($txtree->find_by_tag_name($badtag)) {
+ $element->delete() if defined $element;
+ }
+ }
+ # Проверяем на наличие URL-ок не оформленных ссылками.
+ return $txtree;
+}
+
+
+
+sub str2tree {
+ my ($data)=@_;
+ my $tree = HTML::TreeBuilder->new();
+ # Set parser options here
+ $tree->parse("<html><body><div>$data</div></body></html>");
+ $tree->eof;
+ my $element=$tree->find("body");
+ while (($element =($element->content_list)[0])->tag ne "div") {
+ }
+ $element->detach;
+ $tree->destroy;
+ return $element;
+}
+
+sub tree2str {
+ my ($tree)=@_;
+ return $tree->as_HTML("<>&");
+}
+
+#------------------------------------------------------------------------
+# Подстановка в дереве
+#------------------------------------------------------------------------
+# Находит
+# элемент указанного класса и удаляет display: none из его атрибута
+# style. Возвращает 1, если элемент был раскрыт, и 0, если он и до этого
+# был видимым.
+sub unhide_list {
+ my ($tree,$class) = @_;
+ my $msglist = $tree->look_down("class"=>$class);
+ if ($msglist) {
+ my $style = $msglist->attr("style");
+ if ($style && $style =~ s/display: none;//) {
+ $msglist->attr("style",$style);
+ return 1;
+ } else {
+ return 0;
+ }
+ }
+}
+#
+# Находит первый элемент указанного класса, и приписывает ему display:
+# none в style.
+#
+sub hide_list {
+ my ($tree,$class)=@_;
+ my $msglist = $tree->look_down("class"=>$class);
+ return undef unless $msglist;
+ if (!$msglist->attr("style")) {
+ $msglist->attr("style","display: none;");
+ } else {
+ my $style = $msglist->attr("style");
+ unless ($style=~ s/\bdisplay:\s+\w+\s*;/display: none;/) {
+ $style .= "display: none;";
+ }
+ $msglist->attr("style",$style);
+ }
+ return 1;
+}
+#
+# Найти все элементы, удоволетворяющие заданному критерию и подставить в
+# них указанные атрибуты
+#
+# Параметры 1. Дерево (класса HTML::Element)
+# 2. Запрос - ссылка на список вида атрибут=>значение.
+# Этот список будет непосредственно передан в
+# HTML::Element::look_down
+# 3. Далее пары имя-атрибута, значение. Если вместо имени атрибута
+# использовать слово _content, заменено будет содержимое элемента.
+# Значение для _content - ссылка на HTML::Element. Если там строка,
+# она будет вставлена как одиночный текстовый узел.
+# 4. Возвращает число выполненных подстановок (0, если искомых элементов
+# не найдено.
+#
+sub substinfo {
+ my ($tree,$query,@attrs) = @_;
+ my $count;
+ foreach my $element ($tree->look_down(@$query)) {
+ $count ++;
+ while (@attrs) {
+ my $attr = shift @attrs;
+ my $value = shift @attrs;
+ if ($attr eq "_content") {
+ $element->delete_content;
+ $element->push_content($value);
+ } else {
+ $element->attr($attr,$value);
+ }
+ }
+ }
+ return $count;
+}
+#
+# newlistelement($tree,$elementclass,$listclass)
+#
+# Если список с указанным классом скрыт, раскрывает его и возвращает
+# (единственный) элемент
+sub newlistelement {
+ my ($tree,$element,$list) =@_;
+ my $msglist = $tree->look_down("class"=>$list);
+ if ($msglist) {
+ my $style = $msglist->attr("style");
+ if ($style && $style =~ s/display: none;//) {
+ $msglist->attr("style",$style);
+ return $msglist->look_down(class=>$element);
+ } else {
+ my $template = $msglist->look_down("class"=>$element);
+ return undef unless $template;
+ my $newitem=$template->clone;
+ $template->parent->push_content($newitem);
+ return $newitem;
+ }
+ } else {
+ return undef;
+ }
+}