]> www.wagner.pp.ru Git - oss/stilllife.git/blob - forum/forum
*** empty log message ***
[oss/stilllife.git] / forum / forum
1 #!/usr/bin/perl -T
2 #
3 # Stil Life forum. Copyright (c) by Victor B. Wagner, 2008    
4 # This program distributed under GNU Affero General Public License v3 or
5 # above
6 # http://www.gnu.org/licenses/agpl.html
7 #
8 # Вкратце: Если вы используете этот скрипт на своем сайте, Вы обязаны
9 # сделать доступным его исходный текст. В частности, если Вы внесли
10 # какие-либо изменения, вы должны эти изменения опубликовать. 
11
12 # Home site of this program http://vitus.wagner.pp.ru/stilllife
13
14 use strict;
15 use warnings;
16 use Fcntl qw(:DEFAULT :flock);
17 use CGI;
18 use HTML::TreeBuilder;
19 use Storable qw(freeze thaw);
20 use Date::Parse;
21 use Email::Valid;
22 use Image::Size;
23 use HTML::BBReverse;
24 use POSIX;
25 use LWP::UserAgent;
26 use Net::OpenID::Consumer;
27 #
28 # Набор поддерживаемых действий. Хэш вида 
29 # "имя поля в запросе" =>  "функция обработчик"
30 #
31 my %actions = (
32         reply => \&reply,
33         edit => \&edit_comment,
34         delete => \&delete_comment,
35         move => \&move_comment,
36         newtopic=> \&new_topic,
37         newforum=> \&new_forum,
38         login => \&login,
39         register=>\&register,
40         profile=>\&profile,
41         setrights=>\&set_rights,
42         openidlogin=>\&openid_login,
43         openidvfy =>\&openid_verify
44 );      
45 #
46 #  Уровень прав, которые необходимо иметь пользователю для совершения
47 #  определенного действия
48 #  иерархия вида undef < banned < normal < author < moderator <admin
49 #  Если операция не упомянута в данном массив, то значит можно всем, в
50 #  том числе  и анониму.
51 # Слово login означает, что вообще-то это normal, но пользователь может
52 # логиниться непосредственно в процессе выполнения операции.
53 my %permissions = (
54         reply => "login",
55         edit => "author",
56         delete => "author",
57         newtopic => "normal",
58         move => "moderator",
59         newforum => "moderator",
60         profile => "normal",
61         setrights => "admin",
62 );      
63 our $path_translated; # Untainted value of PATH_TRANSLATED env var
64 my $cgi = new CGI;
65 print STDERR "--------------------\n";
66 my $forum=get_forum_config();
67
68 authorize_user($cgi,$forum);
69 if ($cgi->request_method ne "POST") {
70 # Запрос к скрипту методом GET. Надо показать форму, если только это не
71 # редирект от OpenId-сервера 
72         if ($cgi->param('openidvfy')) { 
73                 openid_verify($cgi,$forum);
74         } elsif ($cgi->param("logout")) {
75                 logout('logout',$cgi,$forum);
76         } else {
77                 for my $param ($cgi->param) {
78 # Среди параметров, указанных в URL ищем тот, который задает
79 # действие 
80                         if (exists $actions{$param}) {
81 # Мы, конечно уже проверили, что в названии параметра
82 # нехороших символов нет, но чтобы perl в taint mode не
83 # ругался... 
84                                 if (allow_operation($param,$cgi,$forum)) {
85                                         print STDERR "Allow_operation completed\n";
86                                         show_template($1,$cgi,$forum) if $param=~/^(\w+)$/;     
87                                         exit;
88                                 } else {
89                                         if (!$forum->{"authenticated"}) { 
90                                                 $cgi->param("returnto",$cgi->url(-full=>1));
91                                                 show_template("login",$cgi,$forum);
92                                                 exit;
93
94                                         } else {
95                                                 show_error($forum,"У Вас нет прав на  выполнение этой
96                                                 операции")
97                                         }
98                                 }       
99                         }
100                 }
101                 show_error($forum,"Некорректный вызов скрипта. Отсутствует параметр
102                                 действия");
103         }       
104 } else {
105         # Запрос методом POST. Вызываем обработчик
106         for my $param ($cgi->param) {
107                 if (exists $actions{$param}) {
108                         if (allow_operation($param,$cgi,$forum)) {
109                                 $actions{$param}->($param,$cgi,$forum);
110                                 exit;
111                         } else {
112                                 show_error($forum,"У Вас нет прав на  выполнение этой
113                                 операции")
114                         }
115
116                 }
117         }
118         print STDERR "Получены параметры ",join(" ",$cgi->param),"\n";
119         show_error($forum,"Некорректный вызов скрипта. Отсутствует параметр действия");
120 }       
121
122 sub dir2url {
123         my ($cgi,$dir) = @_;
124         my $prefix="";
125         my $pos=rindex $ENV{'PATH_TRANSLATED'},$ENV{'PATH_INFO'};
126         if ($pos <0 && $ENV{'PATH_INFO'}=~m!(/\~\w+)/!) {
127                 $prefix .=$1;
128                 $pos =
129                 rindex($ENV{'PATH_TRANSLATED'},substr($ENV{'PATH_INFO'},length($1)));
130         }
131         if ($pos <0) {
132                 show_error({},"Ошибка конфигурации форума. Не удается определить
133                 алгоритм преобразования директори в URL\n".
134                 "PATH_INFO=$ENV{PATH_INFO}\n".
135                 "PATH_TRANSLATER=$ENV{'PATH_TRANSLATED'}");
136         }       
137         my $root = substr($ENV{'PATH_TRANSLATED'},0,$pos);
138         if (substr($dir,0,length($root)) ne $root) {
139                 show_error({},"Ошибка конфигурации форума. Не удается преобразовать
140                 имя директории $dir в url\n".
141                 "PATH_INFO=$ENV{PATH_INFO}\n".
142                 "PATH_TRANSLATER=$ENV{'PATH_TRANSLATED'}");
143         }
144         return $prefix.substr($dir,length($root));
145 }
146 #
147 # Поиск файла .forum вверх по дереву от $path_translated  
148 # Значение PATH_TRANSLATED считаем безопасным - наш web-сервер нам не
149 # враг.
150 # Возвращает список имя,значение, имя, значение который прививается в
151 # хэш
152
153 sub get_forum_config {
154         $path_translated = $1 if $ENV{PATH_TRANSLATED}=~/^(\S+)$/;
155         my @path=split("/",$path_translated);
156         while (@path>1) {
157                 if (-r (my $config=join("/",@path,".forum")) ) {
158                         open F,"<",$config;
159                         my %config;
160                         while (<F>) {
161                                 s/#.*$//; #Drop comments;
162                                 $config{$1}=$2 if /(\w+)\s*=\s*(\S.*)$/;
163                         }       
164                         close F;
165                         #
166                         # Переменная forumtop - это URL того места, где находится
167                         # файл .forum
168                          
169                         $config{"forumtop"} = dir2url($cgi,join("/",@path));
170                         # Если в конфиге отсутствует переменная templates, но
171                         # рядом с конфигом присутствует директория templates,
172                         # то шаблоны там.
173                         #
174                         if (! exists $config{"templates"} 
175                                 && -d (my $filename = join("/",@path,"templates"))) {
176                                         $config{"templates"} = $filename;
177                         }               
178                         $config{"templatesurl"} = dir2url($cgi,$config{"templates"})
179                                 unless exists $config{"templatesurl"};
180                         # 
181                         # То же самое - параметр userdir и директория users
182                         #
183                         if (! exists $config{"userdir"} 
184                                 && -d (my $filename = join("/",@path,"users"))) {
185                                         $config{"userdir"} = $filename;
186
187
188                         }       
189                         $config{"userurl"} = dir2url($cgi,$config{"userdir"});
190                         #
191                         # Если нет ссылки в конфиге на файл паролей или он не 
192                         # существует, выдаем ошибку. С офоромлением, так как шаблоны
193                         #  у нас уже есть
194                         if (!exists $config{"datadir"}) {
195                                 show_error(\%config,"В конфигурации форума не указана
196                                 директория данных "); 
197                                 exit;
198                         }
199                         if (!-d $config{"datadir"}) {
200                                 show_error(\%config,"В конфигурации форума указана несуществующая директория данных "); 
201                                 exit;
202                         }
203                         $config{"authperiod"}="+1M" if (! exists $config{"authperiod"}); 
204                         $config{"renewtime"} = "86000" if (!exists $config{"renewtime"});
205                         $config{"replies_per_page"} = 50 if (!exists $config{"replies_per_page"});
206                         $config{"indexfile"} = "index.html" if (!exists $config{"indexfile"});
207                         return \%config;
208                 }
209                 pop @path;
210         }
211         #
212         # Выводим ошибку 404 без осмысленного оформления, так как данных форума
213         # мы не нашли
214         print "Status: 404\nContent-Type: text/html; charset=utf-8\n\n",
215         "<HTML><HEAD><TITLE>Форум не обнаружен</TITLE></HEAD><BODY>",
216         "<H!>Форум не найден</H!>",
217         "<p>Хвост URL, указанный при вызове скрипта  показывает не на
218         форум</p>",
219         # To make IE think this page is user friendly
220         "<!--",("X" x 512),"--></body></html>\n"; 
221         exit;
222 }
223 #
224 # Вывод сообщения об ошибке по шаблону форума
225 # Шаблон должен содержать элемент с классом error.
226 #
227 sub show_error {
228         my ($cfg,$msg) = @_;
229         if ( -r $cfg->{"templates"}."/error.html") {
230                 my $tree = HTML::TreeBuilder->new_from_file($cfg->{"templates"}."/error.html");
231                 my $node= $tree->find_by_attribute('class','error');
232                 my $body;
233                 if (!$node) {
234                         $body = $tree->find_by_tagname('body');
235                         $body->push_content($node = new
236                         HTML::Element('div','class'=>'error'));
237                 }
238                 $node->delete_content;
239                 $node->push_content($msg);
240                 print $cgi->header(-type=>'text/html',-charset=>'utf-8');
241                 print $tree->as_HTML("<>&");
242         } else {
243                 print $cgi->header(-type=>'text/html',-charset=>'utf-8');
244                 print "<html><head><title>Ошибка конфигурации форума</title></head>",
245                 "<body><h1>Ошибка конфигурации форума</h1><p>",
246                 $cgi->escapeHTML($msg),"</p>",
247                 "<p>При обработке этой ошибки не обнаружен шаблон сообщения об ошибке</p></body></html>";  
248         }
249         exit;
250 }       
251
252 #
253 # Вывод шаблона формы. В шаблоне должна присутстовать форма с  
254 # именем, совпадающим с именем form. Если в $cgi есть параметры, имена
255 # которых совпадают с именами полей этой формы, их значения
256 # подставляются
257 #
258 sub show_template {
259         my ($form,$cgi,$forum) = @_;
260         my $tree = gettemplate($forum,$form,$ENV{'PATH_INFO'});
261
262         # Находим форму с классом $form
263         my $f = $tree->look_down("_tag","form",
264                 "name",$form);
265         if (! defined $f) {
266                 # Если не нашли - ругаемся
267                 show_error($forum,"Шаблон для операции $form не содержит формы с
268                 именем $form");
269                 exit;
270         }
271         $cgi->delete('password');
272         if (!$cgi->param("returnto")) {
273                 $cgi->param("returnto", $cgi->referer||$cgi->url(-absolute=>1,-path_info=>1));
274
275         }       
276         if (!$cgi->param($form)) {
277                 $cgi->param($form,1);
278         }       
279         # 
280         # Если ранее была выставлена ошибка с помощью set_error, подставляем
281         # сообщение в элемент с классом error
282         #
283         if ($forum->{error_message}) {
284                 my $errormsg = $tree->look_down("class"=>"error");
285                 if ($errormsg) {
286                         $errormsg->delete_content();
287                         $errormsg->push_content($forum->{error_message});
288                 }
289         }       
290         if ($forum->{"authenticated"}) {
291                  
292                 # Подставляем информацию о текущем пользователе если в шаблоне
293                 # это предусмотрено 
294                 substitute_user_info($tree,$forum);
295                 $cgi->param("user",$forum->{"authenticated"}{"user"}) if (!defined $cgi->param("user"))
296         }
297         my %substituted;
298         ELEMENT:
299         for my $element ($f->find_by_tag_name("textarea","input","select")) {
300                 my $name = $element->attr("name");
301                 $substituted{$name} = 1;
302                 #print STDERR "substituting form element name $name tag ",$element->tag,
303             #           "value='",$cgi->param($name),"'\n";  
304                 if (defined  $cgi->param($name)) {
305                         if ($element->tag eq "input") {
306                                 next ELEMENT if grep ($element->attr("type") eq
307                                 $_,"button","submit","reset");  
308                                 if ($element->attr("type") eq "check") {
309                                         if (grep($element->attr("value") eq $_,$cgi->param($name))) {
310                                                 $element->attr("checked","");
311                                         } else {
312                                                 $element->attr("checked",undef);
313                                         }
314                                 
315                                 } elsif ($element->attr("type") eq
316                                 "radio") {
317                                         if ($element->attr("value") eq $cgi->param($name)) {
318                                                 $element->attr("checked","");
319                                         } else {
320                                                 $element->attr("checked",undef);
321                                         }
322                                 } else {        
323                                 $element->attr("value",$cgi->param($name));
324                                 }
325                         } elsif ($element->tag eq "textarea") {
326                                 $element->delete_content;
327                                 $element->push_content($cgi->param($name));
328                         } elsif ($element->tag eq "select") {
329                                 for my $option ($element->find_by_tag_name("option")) {
330                                         if (grep($option->attr("value") eq $_, $cgi->param($name))) {
331                                                 $option->attr("selected","");
332                                         } else {        
333                                                 $option->attr("selected",undef);
334                                         }       
335                                 }
336
337                         }
338                 }
339
340         }
341         $f->attr("method","POST");
342         for my $required ($form,"returnto") {
343                 if (!$substituted{$required}) {
344                         my $element = new HTML::Element('input',
345                                 'type' => 'hidden', 'name' => $required,
346                                 'value'=> $cgi->param($required));
347                         $f->push_content($element);
348                 }
349         }       
350                                 
351                 
352         print
353         $cgi->header(-type=>"text/html",-charset=>"utf-8",($forum->{cookies}?(-cookie=>$forum->{cookies}):())),
354         $tree->as_HTML("<>&");
355 }
356 #
357 # Поправляет ссылки на служебные файлы и скрипты форума
358 #
359 sub fix_forum_links {
360         my ($forum,$tree,$path_info) = @_;
361         $path_info=$ENV{'PATH_INFO'} if (!defined $path_info);
362         my $script_with_path = $ENV{SCRIPT_NAME}.$path_info;
363         ELEMENT:
364         for my $element ($tree->find_by_tag_name("form","img","link","script","a")) {
365                 my $attr;
366                 if ($element->tag eq "form")  {
367                         $attr = "action";
368                 } elsif ($element->tag eq "a"|| $element->tag eq "link") {
369                         $attr = "href";
370                 } else {
371                         $attr ="src";
372                 }
373                 
374                 # Обрабатываем наши специальные link rel=""
375                 if ($element->tag eq "link") {
376                         if ($element->attr("rel") eq "forum-user-list") {
377                                 $element->attr("href" => $cgi->url(-absolute=>1,
378                                         -path_info=>0,-query_string=>0).$forum->{userurl});
379                                 next ELEMENT;   
380                         } elsif ($element->attr("rel") eq "forum-script")  {
381                                 $element->attr("href" => $script_with_path);
382                                 next ELEMENT;
383                         }       
384                 }
385                 my $link = $element->attr($attr);
386                 # Абсолютная ссылка - оставляем как есть. 
387                 next ELEMENT if (! defined $link || $link=~/^\w+:/ || $link
388                 eq"."||$link eq ".."); 
389                 # Ссылка от корня сайта. 
390                 if (substr($link,0,1) eq "/") {
391                         # Если она не ведет на наш скрипт, не обрабатываем
392                         next ELEMENT if substr($link,0,length($ENV{SCRIPT_NAME}) ne
393                         $ENV{SCRIPT_NAME}) ;
394                         # Иначе пишем туда слово forum вместо реального имени
395                         # скрипта чтобы потом единообразно обработать
396                         $link =~ s/^[^\?]+/forum/;
397                 }
398                 if (!($link =~ s!^templates/!$forum->{templatesurl}/!) &&
399                     !($link =~ s!^users/!$forum->{usersurl}/!) &&
400                     !($link =~ s!^forum\b!$script_with_path!)) {
401                         $link = $forum->{"forumtop"}."/".$link 
402                 }       
403                 $element->attr($attr,$link);
404         }
405 }               
406 #
407 # Подставляет в заданное поддерево информацию о пользователе
408 #
409
410 sub substitute_user_info {
411
412 my ($tree,$forum,$user) = @_;
413 my %userinfo;
414 if (defined $user) {
415         my %users;
416         dbmopen %users,datafile($forum,"passwd"),0644;
417         if (!$users{$user}) {
418                 show_error($forum,"Неизвестный пользователь $user");
419         }
420         my $record = thaw($users{$user});
421         %userinfo = %$record;
422         $userinfo{"user"} = $user;
423 } else {
424         # Если не сказано, какой юзер, то текущий.
425         %userinfo = %{$forum->{"authenticated"}}  
426 }
427
428 #
429 # Специально обрабатываем поля user (должна быть ссылка) и avatar  
430 # (должен быть img).
431         my $userpage;
432         if ($userinfo{"openiduser"}) {
433                 $userpage = "http://".$userinfo{"user"};
434         } else {
435                 $userpage =
436                 $cgi->url(-absolute=>1).$forum->{"userurl"}."/".$cgi->escape($userinfo{"user"});
437         }       
438         substinfo($tree,["_tag"=>"a","class"=>"author"],
439          href=>$userpage,_content=>$userinfo{"user"});
440         delete $userinfo{"user"};
441         substinfo($tree,["_tag"=>"img","class"=>"avatar"],
442         src=>$userinfo{"avatar"}||$forum->{templatesurl}."/1x1.gif");
443         delete $userinfo{"avatar"};
444
445         for my $element ( $tree->look_down("class",qr/^ap-/)) {
446                 my $field=$1 if $element->attr("class")=~/^ap-(.*)$/;   
447                 $element->delete_content();
448                 $element->push_content(str2tree($userinfo{$field})) 
449                                 if $userinfo{$field};
450                 $element->attr(href=>"mailto:$userinfo{$field}") 
451                         if ($element->tag eq "a" && $field eq "email");
452         }
453
454
455 }
456 #
457 # Авторизует зарегистрированного пользователя.
458 # 1. Проверяет куку если есть
459 #
460
461 sub authorize_user      {
462         ($cgi,$forum) = @_;
463         if (my $session=$cgi->cookie("slsession")) {
464         # Пользователь имеет куку
465                 my %sessbase;   
466                 dbmopen %sessbase,datafile($forum,"session"),0644;
467                         if ($sessbase{$session})  {
468                                 my ($user,$expires,$ip)=split(";", $sessbase{$session});
469                                 my $user_cookie = $cgi->cookie("sluser");
470                                 if ($user_cookie ne $user && $user_cookie ne
471                                 "http://".$user) {
472                                         clear_user_cookies($cgi,$forum);
473                                         show_error($forum,"Некорректная пользовательская сессия");
474                                         exit;
475                                 }       
476                                 if (!defined $ip|| $ip eq $ENV{'REMOTE_ADDR'}) {
477                                         my %userbase;
478                                         dbmopen %userbase,datafile($forum,"passwd"),0644;
479                                         if ( $userbase{$user}) {
480                                                 print STDERR "getting user info for $user\n";
481                                                 my $userinfo = thaw($userbase{$user});
482                                                 delete $userinfo->{"passwd"};
483                                                 $userinfo->{"user"} = $user;
484                                                 if ($expires-time()< $forum->{"renewtime" }) {
485                                                         delete $sessbase{$session};
486                                                         newsession(\%sessbase,$forum,$user,$ip);
487                                                 }
488                                                 print STDERR "user $user restored session $session\n";
489                                                 $forum->{"authenticated"}=$userinfo;
490                                                 print STDERR "authorize_user: ",$forum->{authenticated}{user},
491                                                 $forum->{authenticated},"\n";
492                                         }       
493                                         dbmclose %userbase; 
494                                 }       
495                         } else {
496                                 clear_user_cookies($cgi,$forum);
497                                 show_error($forum,"Некорректная пользовательская сессия");
498                                 exit;
499                         }
500                 dbmclose %sessbase;
501         }
502 }
503 #
504 # Возвращает путь к файлу в директории 
505 #
506 sub datafile {
507         my ($forum,$filename) = @_;
508         return $forum->{"datadir"}."/".$filename;
509 }       
510
511 #
512 # Создает новую сессию для пользователя и подготавливает куку которую
513 # сохраняет в хэше конфигурации форума
514
515 sub newsession {
516         my ($base,$forum,$user,$bindip) = @_;
517         if (!defined $base) {
518                 $base = {};
519                 dbmopen %$base,datafile($forum,"session"),0644;
520         }       
521         my $sessname;
522         my $t = time();
523         my ($u,$expires,$ip);
524         do {
525                 $sessname = sprintf("%08x",rand(0xffffffff));
526                 if ($base->{"sessname"}) {
527                         ($u,$expires,$ip) = split ";", $base->{$sessname};
528                         delete $base->{$sessname} if $expires < $t;
529                 }
530         } while ($base->{$sessname});
531         my $cookie = $cgi->cookie(-name=>"slsession",
532                 -expires => $forum->{"authperiod"},-value=> $sessname);
533         my $username = $user;
534         $username =~ s/^http:\/\///; #Remoove http:// from OpenID user names 
535         $base->{$sessname}=$username.";".str2time($cookie->expires()).
536                 ($ip?";$ENV{'REMOTE_ADDR'}":"");
537                 
538         $forum->{'cookies'}=[ $cookie,
539         $cgi->cookie(-name=>"sluser",-value=>$user,-expires =>
540         $forum->{authperiod})];                         
541 }
542 #
543 # Выполняет аутентикацию пользователя по логину и паролю и 
544 # создает для него сессию.
545 #
546 sub authenticate {
547         my ($cgi,$forum) = @_;  
548         if ($cgi->param("openidsite")) {
549                 my $openid_url = sprintf($cgi->param("openidsite"),$cgi->param("user"));
550                 openidstart($cgi,$forum,$openid_url);
551         }       
552         my %userbase;
553         dbmopen %userbase,datafile($forum,"passwd"),0644;
554         my $user = $cgi->param("user");
555         my $password = $cgi->param("password");
556         $cgi->delete("password");
557         if (! $userbase{$user}) {
558           set_error($forum,"Неверное имя пользователя или пароль");
559           return undef;
560         }   
561         my $userinfo = thaw($userbase{$user}) ;
562         dbmclose %userbase;
563         #while (my ($key,$val)=each %$userinfo) { print STDERR "$key => '$val'\n";}
564         if (crypt($password,$userinfo->{passwd}) eq $userinfo->{passwd}) {
565                 delete $userinfo->{"passwd"};
566                 $cgi->delete("password");
567                 $userinfo->{"user"} = $user;
568                 newsession(undef,$forum,$user);
569                 $forum->{"authenticated"} = $userinfo;          
570                 print STDERR "User $user authenticated successfully\n";
571                 return 1;
572         } else {
573                 set_error($forum,"Неверное имя пользователя или пароль");
574                 return undef;
575         }       
576 }
577 #
578 # Запоминает сообщение об ошибке для последующего вывода show_template
579 #
580 sub set_error {
581         my  ($forum,$message) = @_;
582         print STDERR "set_error: $message\n";
583         $forum->{error_message} = $message;
584 }       
585 #
586 # Выводит текущий шаблон с сообщением об ошибке
587 #
588 sub form_error {
589         my ($form_name,$cgi,$forum,$msg) = @_;
590         set_error($forum,$msg);
591         show_template($form_name,$cgi,$forum);
592         exit;
593 }       
594 #
595 # Выполняет редирект (возможно, с установкой куков) на страницу,
596 # указанную # третьем параметре функции или в параметре CGI-запроса
597 # returnto
598 # Если и то, и другое не определено, пытается сконструировать URL для
599 # возврата из PATH_INFO.
600 #
601
602 sub forum_redirect {
603         my ($cgi,$forum,$url) = @_;
604         if (!defined $url) {
605                 $url = $cgi->param("returnto");
606                 $url =
607                 $cgi->url(-base=>1).($cgi->path_info()||$forum->{forumtop}) if !$url ;
608         }
609         print $cgi->redirect(-url=>$url,
610                 ($forum->{cookies}?(-cookie=>$forum->{cookies}):()));
611         exit;   
612 }
613 #
614 # Обработка результатов заполнения формы регистрации.
615 #
616 #
617 sub register {
618         my ($formname,$cgi,$forum) = @_; 
619         #
620         # Возможные ошибки: 
621         # 1 Такой юзер уже есть
622         #
623         #  не заполнено поле user 
624         if (!$cgi->param("user")) {
625                 form_error($formname,$cgi,$forum, "Не заполнено имя пользователя");
626         }       
627         #  или поле password 
628         if (!$cgi->param("pass1"))  {
629                 form_error($formname,$cgi,$forum,"Не указан пароль");
630         }       
631         #  Копии пароля не совпали
632         if ($cgi->param("pass2") ne $cgi->param("pass1")) {
633                 form_error($formname,$cgi,$forum,"Ошибка при вводе пароля");
634         }               
635         my $user = $cgi->param("user");
636         # Не указаны поля, перечисленные в скрытом поле required 
637         if ($cgi->param("required")) { 
638                 foreach my $field (split(/\s*,\s*/,$cgi->param('required'))) {
639                         if (!$cgi->param($field)) {
640                                 form_error($formname,$cgi,$forum,"Не заполнено обязательное поле $field");
641                         }
642                 }       
643         }
644         my %userbase;
645         dbmopen %userbase,datafile($forum,"passwd"),0644 
646                 or form_error($formname,$cgi,$forum,"Ошибка открытия файла паролей $!");
647         if ($userbase{$cgi->param("user")}) {
648                 dbmclose %userbase;
649                 form_error($formname,$cgi,$forum,"Имя пользователя '".$cgi->param("user"). "' уже занято");
650         }
651         if ($cgi->param("email") && !  Email::Valid->address($cgi->param("email"))) {
652                 form_error($formname,$cgi,$forum,"Некорректный E-Mail адрес");
653         }
654         my $saltstring = 'ABCDEFGHIJKLMNOPQRSTUVWXUZabcdefghijklmnopqrstuvwxuz0123456789./';
655         my $salt = substr($saltstring,int(rand(64)),1).
656                                 substr($saltstring,int(rand(64)),1);
657         my $password=crypt($cgi->param("pass1"),$salt);                 
658         my $userinfo = {passwd=>$password};
659         # Удаляем лишние поля
660         $cgi->delete("required");
661         $cgi->delete("register");
662         $cgi->delete("user");
663         $cgi->delete("pass1");
664         $cgi->delete("pass2");
665         foreach my $field (split(/\s*,\s*/,$cgi->param('ignore'))) {
666                 if (!$cgi->param($field)) {
667                         $cgi->delete($field);
668                 }
669         }       
670         my $returnto = $cgi->param("returnto");
671         $cgi->delete("returnto");
672         # Если есть аватар в файле, то сохраняем этот файл и формируем URL
673         # на него.
674         if ($cgi->param("avatarfile" )) {
675                 my $f = $cgi->upload("avatarfile");
676                 binmode $f,":bytes";
677                 my $out;
678                 my $filename = $1 if $cgi->param("avatarfile")=~/([^\/\\]+)$/;
679                 open $out,">",$forum->{"userdir"}."/".$filename;
680                 binmode $out,":bytes";
681                 my $buffer;
682                 while (my $bytes = read($f,$buffer,4096)) {
683                         print $out $buffer;
684                 }       
685                 close $f;
686                 close $out;
687                 $userinfo->{'avatar'}= $forum->{"userurl"}."/".$filename;
688                 $cgi->delete("avatar");
689                 $cgi->delete("avatarfile");
690         }
691         
692         foreach my $param       ($cgi->param) {
693                 $userinfo->{$param} = $cgi->param($param);
694         }
695         $userinfo->{registered} = time;
696         if (exists $forum->{default_status}) {
697                 $userinfo->{status} = $forum->{default_status};
698         }
699         print STDERR "stilllife forum: registering user $user\n";
700         $userbase{$user} = freeze($userinfo);
701         dbmclose %userbase;
702         newsession(undef,$forum,$user);
703         forum_redirect($cgi,$forum,$returnto) 
704 }       
705 sub clear_user_cookies {
706         my ($cgi,$forum) = @_;
707         $forum->{cookies}=[ $cgi->cookie(-name=>"sluser", -value=>"0",
708         -expires=>"-1m"),$cgi->cookie(-name=>"slsession", -value=>"0",
709                         -expires => "-1m")];
710 }                       
711 #
712 # Обработчик формы логина. Сводится к вызову функции authenticate,
713 # поскольку мы поддерживаем логин одновременный с отправкой реплики. 
714 #
715 sub login {
716         my ($form,$cgi,$forum)=@_;
717         if (authenticate($cgi,$forum)) {
718                 forum_redirect($cgi,$forum);
719         } else {
720                 show_template(@_);
721         }       
722 }       
723 #
724 # Обработчик формы logout. В отличие от большинства обработчиков форм,
725 # поддерживает обработку методом GET
726 #
727 sub logout {
728         my ($form,$cgi,$forum) = @_;
729         clear_user_cookies($cgi,$forum);
730         if (defined (my $session_id = $cgi->cookie("slsession"))) {
731                 my %sessiondb;
732                 dbmopen %sessiondb,datafile($forum,"session"),0644;
733                 delete $sessiondb{$session_id};
734                 dbmclose %sessiondb;
735         }
736         forum_redirect($cgi,$forum);
737 }       
738 sub allow_operation {
739         my ($operation,$cgi,$forum) = @_;
740         return 1 if (!exists($permissions{$operation})); 
741         if (!$forum->{authenticated}) {
742                 return 1 if ($permissions{$operation} eq "login");
743                 return 0;
744         }       
745         my $user = $forum->{authenticated}{user} ;
746         my $accesslevel=getrights($cgi,$forum);
747         # Если permissions{$operation} равны author, нам нужно извлечь
748         # текст из соответствующего файла и положить его в
749         # cgi->param("text"); Заодно определим и автора
750         my ($itemauthor,$itemtext)=get_message_by_id($cgi->param("id")) if
751                 $permissions{$operation} eq "author";
752         
753         return 1 if ($accesslevel eq "admin");
754         return 0 if ($permissions{$operation} eq "admin");      
755         return 1 if ($accesslevel eq "moderator");
756         return 0 if $accesslevel eq "banned";   
757         return 0 if $permissions{$operation} eq "author" && $user ne $itemauthor;
758         return 1;
759 }
760
761 sub reply {
762         my ($form,$cgi,$forum) = @_;
763         if (! exists $forum->{authenticated} ) {
764                 form_error($form,$cgi,$forum,"Вы не зарегистрировались") if (!authenticate($cgi,$forum)); 
765         }
766         #
767         # Находим файл дискуссии, в который надо поместить реплику
768         #
769         my ($tree,$lockfd)=gettree($path_translated); 
770         my $newmsg = newlistelement($tree,"message","messagelist");
771         if (!$newmsg) {
772                 show_error($forum,"Шаблон темы не содержит элемента с классом
773                 message");
774                 exit;
775         }       
776         
777         #       
778         # Генерируем идентификатор записи.
779         #
780         my $id = get_uid($forum);
781
782
783         #
784         # Сохраняем приаттаченные картинки, если есть.
785         #
786         my $dir = $path_translated;
787
788         $dir=~ s/[^\/]+$// if (-f $dir);
789         my %attached;
790         for (my $i=1;$cgi->param("image$i"); $i++) {
791                 my $userpath=$cgi->param("image$i");
792                 my $filename=lc($1) if $userpath =~ /([^\/\\]+)$/;
793                 $attached{$filename} = $id."_".$filename;
794                 my $in = $cgi->upload("image$i");
795                 if (!$in) {
796                         show_error($forum,"Ошибка при загрузке картинки $filename");
797                         exit;
798                 }       
799                 my $out;
800                 open $out,">$dir/$attached{$filename}";
801                 binmode $out,":bytes";
802                 local $/=undef;
803                 my $data = <$in>;
804                 print $out $data;
805                 close $in;
806                 close $out;
807         }
808         #
809         # Преобразуем текст записи в html и чистим его
810         #
811         my $txtree = input2tree($cgi,$forum,"text");
812         #
813         # Находим в тексте URL на приаттаченные картинки и меняем на те
814         # имена, под которыми мы их сохранили.
815         #
816         for my $image ($txtree->find_by_tag_name("img")) {
817                 my $file=lc($image->attr("src"));
818                 if ( exists $attached{$file}) {
819                         $image->attr("src" => $attached{$file});
820                         my ($width,$height) = imgsize($dir ."/".$attached{$file});              
821                         $image->attr("width" =>$width);
822                         $image->attr("height" => $height);
823                 }       
824         }       
825         #
826         # Подставляем данные сообщения 
827         #
828         $newmsg->attr("id"=>$id);
829         substinfo($newmsg,[class=>"subject"],_content=>$cgi->param("subject"));
830         my $textnode=$newmsg->look_down("class"=>"mtext");
831         if (!$textnode) {
832                 show_error($forum,"В шаблоне реплики нет места для текста"); 
833         }       
834         $textnode->delete_content();
835         $textnode->push_content($txtree);
836         if ($forum->{authenticated}{signature}) {
837                 $textnode->push_content(new HTML::Element("br"),"--",
838                 new HTML::Element("br"),str2tree($forum->{authenticated}{signature}));
839         }
840         substitute_user_info($newmsg,$forum);
841         #
842         # Подставляем данные в форму msginfo
843         #
844         my $editform=$newmsg->look_down(_tag=>"form","class"=>"msginfo");
845         if ($editform) {
846                 substinfo($editform,[_tag=>"input",name=>"id"],value=>$id) ||
847                         show_error($forum,"В форме управления сообщением нет поля id");
848                 substinfo($editform,[_tag=>"input",name=>"author"],value=>
849                         $forum->{authenticated}{user}) ||
850                         show_error($forum,"В форме управления сообщением нет поля author");
851         }
852         # Подставляем mdate
853         substinfo($newmsg,["class"=>"mdate"],
854                 _content =>strftime("%d.%m.%Y %H:%M",localtime()));
855         # Подставляем mreply
856         substinfo($newmsg,[_tag=>"a","class"=>"mreply"],"href" =>
857          $cgi->url(-absolute=>1,-path_info=>1)."?reply=1&id=$id");
858         # Подставляем manchor
859         substinfo($newmsg,[_tag=>"a","class"=>"manchor"],
860                 "name"=>"#$id","href"=>undef) or
861                 show_error($forum,"В шаблоне сообщения отсутствует якорь для ссылок на него");
862         # подставляем mlink
863         substinfo($newmsg,[_tag=>"a","class"=>"mlink"],
864                 href=>$cgi->path_info."#id");
865         # подставляем mparent
866         my $parent_id=$cgi->param("id");
867         if ($parent_id) {
868                 substinfo($newmsg,[_tag => "a",class=>"mparent"], 
869                         "href"=>$cgi->path_info."#$parent_id",style=>undef);
870         } else {
871                 substinfo($newmsg,[_tag => "a",class=>"mparent"], 
872                         style=>"display: none;");
873         }       
874
875         #
876         # Делаем Уфф и сохраняем то, что получилось 
877         #
878         savetree($path_translated,$tree,$lockfd);
879         record_statistics($forum,"message"),
880         forum_redirect($cgi,$forum);
881          
882 }       
883 #
884 # Обработка операции создания новой темы. 
885 #
886
887 sub new_topic {
888         my ($form,$cgi,$forum) = @_;
889         #
890         # Проверяем корректность urlname и прочих полей
891         #
892         my $urlname;
893         if (!$cgi->param("urlname")) {
894                 $urlname = get_uid($forum);
895         } else {        
896                 $urlname=$1 if $cgi->param("urlname") =~ /^([-\w]+)$/;
897                 form_error($form,$cgi,$forum,"Некорректные символы в urlname.
898                 Допустимы только латинские буквы, цифры и минус") unless $urlname; 
899         }
900         if (!-d $path_translated) {
901                 show_error($forum,"Операция $form может быть вызвана только со
902                 страницы форума");
903         }       
904         my $filename = "$path_translated/$urlname.html";
905         if (-f $filename) {
906                 form_error($form,$cgi,$forum,"Тема с urlname $urlname уже
907                 существует");
908         }       
909         if (!$cgi->param("title")) {
910                 form_error($form,$cgi,$forum,"Тема должна иметь непустое название");
911         }       
912         #
913         # Создаем собственно тему
914         #
915         my $tree = gettemplate($forum,"topic",$cgi->path_info."/$urlname.html");
916     # Заполнить название и аннотацию 
917         my $abstract = input2tree($cgi,$forum,"abstract");
918         substinfo($tree,[_tag=>"meta","name"=>"description"],content=>$abstract->as_trimmed_text);
919         substinfo($tree,[_tag=>"title"],_content=>$cgi->param("title"));
920         my $subtree = $tree->look_down("class"=>"topic");
921         my $creation_time=strftime("%d.%m.%Y %H:%M",localtime());
922         if ($subtree) {
923                 substinfo($subtree,["class"=>"title"],
924                 _content=>$cgi->param("title"));
925                 substinfo($subtree,["class"=>"date"],
926                         _content=>$creation_time);
927                 # Вставляем в страницу КОПИЮ аннотации, поскольку аннотация
928                 # нам еще понадобится в списке тем.
929                 substinfo($subtree,["class"=>"abstract"],_content=>$abstract->clone);   
930                 substitute_user_info($subtree,$forum);  
931         } else {
932                 substinfo($tree,["class"=>"title"],
933                 _content=>$cgi->param("title"));
934         }       
935         # Скрыть список сообщений.
936         hide_list($tree,"messagelist");
937         savetree($filename,$tree,undef);
938         $tree->destroy;
939         #
940         # Добавляем элемент в список тем текущего форума
941         #
942
943         my $lockfd;
944         ($tree,$lockfd)=gettree($path_translated."/".$forum->{"indexfile"});
945         my $newtopic = newlistelement($tree,"topic","topiclist");
946         substinfo($newtopic,[_tag=>"a","class"=>"title"],
947         _content=>$cgi->param("title"), href=>"$urlname.html");
948         substinfo($newtopic,["class"=>"date"], _content=>$creation_time);
949         substinfo($newtopic,["class"=>"abstract"],_content=>$abstract); 
950         substitute_user_info($newtopic,$forum); 
951         $newtopic->attr("id",$urlname);
952         my $controlform = $newtopic->look_down(_tag=>"form",class=>"topicinfo");
953         if ($controlform) {
954                 $controlform->attr("action"=>$cgi->url(-absolute=>1,-path_info=>1).
955                 "/$urlname.html");
956                 substinfo($controlform,[_tag=>"input",name=>"author"],value=>
957                         $forum->{authenticated}{user});
958         }               
959         savetree($path_translated."/".$forum->{"indexfile"},$tree,$lockfd);
960         record_statistics($forum,"topic");
961         forum_redirect($cgi,$forum,$cgi->path_info."/$urlname.html");
962 }
963
964 sub new_forum {
965         my ($form,$cgi,$forum) = @_;
966         #
967         # Проверяем корректность urlname и прочих полей
968         #
969         my $urlname;
970          if (!$cgi->param("urlname")) {
971                 form_error($form,$cgi,$forum,"Форуму необходимо задать непустое urlname");
972          }     
973          if ($cgi->param("urlname") eq ".") {
974                 $urlname = "."
975          } else {       
976                 $urlname=$1 if $cgi->param("urlname") =~ /^([-\w]+)$/ ;
977                 form_error($form,$cgi,$forum,"Некорректные символы в urlname.
978                         Допустимы только латинские буквы, цифры и минус") unless $urlname; 
979         }
980         if (!-d $path_translated) {
981                 show_error($forum,"Операция $form может быть вызвана только со
982                 страницы форума");
983         }       
984         my $newname = "$path_translated/$urlname";
985         $newname=$path_translated if ($urlname eq ".");  
986         my $filename = "$newname/$forum->{indexfile}";
987         if (-f $filename) {
988                 form_error($form,$cgi,$forum,"Форум $urlname уже существует");
989         }       
990         if (!$cgi->param("title")) {
991                 form_error($form,$cgi,$forum,"Форум должен иметь непустое название");
992         }
993         mkdir $newname unless -d $newname;
994         #
995         # Сохраняем логотип
996         #
997         my ($logo_name,$logo_width,$logo_height);
998         if ($cgi->param("logo")) {
999                 my $userpath = $cgi->param("logo");
1000                 $logo_name="logo.".lc($1) if $userpath=~/\.([^.]+)$/;
1001                 my $in = $cgi->upload("logo");
1002                 if (!$in) {
1003                         show_error($forum,"Ошибка при загрузке картинки $userpath");
1004                         exit;
1005                 }       
1006                 my $out;
1007                 open $out,">$newname/$logo_name";
1008                 binmode $out,":bytes";
1009                 local $/=undef;
1010                 my $data = <$in>;
1011                 print $out $data;
1012                 close $in;
1013                 close $out;
1014                 ($logo_width,$logo_height) = imgsize("$newname/$logo_name");
1015         } else {
1016                 $logo_name = $forum->{"templatesurl"}."/1x1.gif";
1017                 $logo_width = 1;
1018                 $logo_height=1;
1019         }       
1020
1021
1022         #
1023         # Создаем собственно оглавление форума
1024         #
1025         
1026
1027         my $tree = gettemplate($forum,"forum",$cgi->path_info."/$urlname");
1028     # Заполнить название и аннотацию 
1029         my $abstract = input2tree($cgi,$forum,"abstract");
1030         substinfo($tree,[_tag=>"meta","name"=>"description"],content=>$abstract->as_trimmed_text);
1031         substinfo($tree,[_tag=>"title"],_content=>$cgi->param("title"));
1032         my $subtree = $tree->look_down("class"=>"annotation")
1033                 or show_error($forum,"В шаблоне форума отсутствует класс annotation");
1034         my $creation_time=strftime("%d.%m.%Y %H:%M",localtime());
1035                 substinfo($subtree,["class"=>"title"],
1036                 _content=>$cgi->param("title"));
1037                 substinfo($subtree,["class"=>"date"],
1038                         _content=>$creation_time);
1039                 # Вставляем в страницу КОПИЮ аннотации, поскольку аннотация
1040                 # нам еще понадобится в списке тем.
1041                 substinfo($subtree,["class"=>"abstract"],_content=>$abstract->clone);   
1042                 substitute_user_info($subtree,$forum);  
1043         substinfo($subtree,[_tag=>"img","class"=>"logo"],
1044                 src=> $logo_name, width=>$logo_width, height=>$logo_height);
1045         # Скрыть списки подфорумов и тем .
1046         hide_list($tree,"forumlist");
1047         hide_list($tree,"topiclist");
1048         if ($urlname eq ".") {
1049                 for my $link_up ($tree->look_down(_tag=>"a",href=>"..")) {
1050                         $link_up->delete;
1051                 }
1052         }       
1053         savetree($filename,$tree,undef);
1054         $tree->destroy;
1055         #
1056         # Добавляем элемент в список тем текущего форума
1057         #
1058         if ($urlname ne ".") {
1059         my $lockfd;
1060         ($tree,$lockfd)=gettree($path_translated."/".$forum->{"indexfile"});
1061         my $newforum = newlistelement($tree,"forum","forumlist");
1062         substinfo($newforum,[_tag=>"a","class"=>"title"],
1063         _content=>$cgi->param("title"), href=>"$urlname/");
1064         substinfo($newforum,["class"=>"date"], _content=>$creation_time);
1065         substinfo($newforum,["class"=>"abstract"],_content=>$abstract); 
1066         substinfo($newforum,[_tag=>"img","class"=>"logo"],src=>"$urlname/$logo_name",
1067                 width=>$logo_width,height=>$logo_height);
1068         substitute_user_info($newforum,$forum); 
1069         $newforum->attr("id",$urlname);
1070         my $controlform = $newforum->look_down(_tag=>"form",class=>"foruminfo");
1071         if ($controlform) {
1072                 $controlform->attr("action"=>$cgi->url(-absolute=>1,-path_info=>1).
1073                 "/$urlname");
1074                 substinfo($controlform,[_tag=>"input",name=>"author"],value=>
1075                         $forum->{authenticated}{user});
1076         }               
1077         savetree($path_translated."/".$forum->{"indexfile"},$tree,$lockfd);
1078         record_statistics($forum,"forum");
1079         }
1080         forum_redirect($cgi,$forum,$cgi->path_info."/$urlname");
1081 }
1082         
1083 #---------------------------------------------------------- 
1084 # База пользователей и права доступа
1085 #----------------------------------------------------------
1086 #
1087 # Записывает в базу данных пользователей, сколько каких объектов 
1088 # создал текущий пользователь
1089 #
1090 sub record_statistics {
1091         my ($forum,$type) = @_;
1092         my $user = $forum->{authenticated}{user};
1093         my %base;
1094         dbmopen %base,datafile($forum,"passwd"),0664;
1095         my $userinfo = thaw($base{$user});
1096         $userinfo->{$type."s"}++;
1097         $userinfo->{"last_$type"}=time;
1098         $base{$user} = freeze($userinfo);
1099         dbmclose %base;
1100 }
1101 #
1102 # читает файлы прав доступа в дереве форума, и возвращает
1103 # статус текущего пользователя (undef - аноним, banned, normal,
1104 # moderator или admin
1105
1106 sub getrights {
1107         my ($cgi,$forum) = @_;
1108         if (!$forum->{authenticated}) {
1109                 return undef;
1110         }       
1111         my $user = $forum->{authenticated}{user};
1112         my $dir = $path_translated;
1113         $dir =~s/\/$//;
1114         $dir =~s/\/[^\/]+$// if (!-d $dir);
1115         my $f;
1116         my $user_status = "normal";
1117         LEVEL:
1118         while (length($dir)) {  
1119                 print STDERR "Searcghing for perms in $dir\n";
1120                 if (-f "$dir/perms.txt") {
1121                         open $f,"<","$dir/perms.txt";
1122                         my $status = undef;
1123                         while (<$f>) {
1124                                 if (/^\[\s*(admins|moderators|banned)\s*\]/) {
1125                                         $status = $1;
1126                                 } else {
1127                                         chomp;
1128                                         if  ($user eq $_ && defined $status) {
1129                                                 if ($status eq "banned") {
1130                                                         return $status;
1131                                                 } 
1132                                                 if ($status eq "admins" ) {
1133                                                         return "admin";
1134                                                 }
1135                                                 $user_status = "moderator";
1136                                         }
1137                                 }       
1138                         }
1139                         close $f;
1140                         last LEVEL if  -f "$dir/.forum";
1141                 }       
1142                 # Strip last path component.
1143                 $dir =~s/\/[^\/]+$// 
1144         }               
1145         return $user_status;
1146
1147 }               
1148
1149
1150
1151 #------------------------------------------------------------------
1152 # Работа с файлами и идентификторами
1153 #------------------------------------------------------------------
1154
1155 #
1156 # Залочить файл и получить его распрасенное представление.
1157 # Возвращает пару ($tree,$lockfd)
1158
1159 sub gettree {
1160         my $filename = shift;
1161         my $f;
1162         open $f,"<",$filename or return undef;
1163         flock $f, LOCK_EX;
1164         my $tree = HTML::TreeBuilder->new_from_file($f);
1165         return ($tree,$f);
1166 }       
1167 #
1168 # Сохранить дерево и закрыть lockfd.
1169 #
1170 #
1171
1172 sub savetree {
1173         my ($filename,$tree,$lockfd) = @_;
1174         my $f;
1175         open $f,">",$filename . ".new" or return undef;
1176         print $f $tree->as_HTML("<>&");
1177         close $f;
1178         # FIXME - только для POSIX.
1179         unlink $filename;
1180         rename $filename.".new",$filename;
1181         close $lockfd if defined($lockfd);
1182 }       
1183 #
1184 # Читает шаблон и подготавливает его к размещению по указанной URL.
1185 # Если url не указана, считается что шаблон будет показан как результат
1186 # текущего http-запроса.
1187
1188 sub gettemplate {
1189         my ($forum, $template,$url) = @_;
1190         my $filename=$forum->{"templates"}."/$template.html";
1191         if (! -r $filename) {
1192                 show_error($forum,"Нет шаблона $template");
1193                 exit;
1194         }
1195         my $tree = HTML::TreeBuilder->new_from_file($filename);
1196         fix_forum_links($forum,$tree,$url);
1197         return $tree;
1198 }       
1199
1200
1201 #
1202 # Получает уникальный числовой идентификатор.
1203
1204 sub get_uid {
1205         my $forum = shift;
1206         my $f;
1207         open $f,"+<",datafile($forum,"sequence") or 
1208         flock $f,LOCK_EX;
1209         my $id=<$f> || "0";
1210         $id++;
1211         seek $f,0,0;
1212         printf $f "%8s\n",$id;
1213         close $f;
1214         $id=~/(\d+)/;
1215         return sprintf ("%08s",$1);
1216 }
1217 # --------------------------------------------------------------------
1218 #  OpenID registration
1219 # -------------------------------------------------------------------
1220 sub create_openid_consumer {
1221         my ($cgi,$forum) = @_;
1222         return Net::OpenID::Consumer ->new(
1223                 ua => LWP::UserAgent->new(),
1224                 args => $cgi,
1225                 consumer_secret=>"X9RWPo0rBE7yLja6VB3d",
1226                 required_root => $cgi->url(-base=>1));
1227 }               
1228
1229 # openidstart - вызывается когда обнаружено что текущее имя
1230 # пользователя, пытающегося аутентифицироваться, содержит http://
1231 #  
1232 #
1233
1234 sub openidstart {
1235         my ($cgi,$forum,$openidurl) = @_;
1236         #
1237         # Fix duplicated http:// which can be produced by our sprintf based
1238         # login system
1239         #
1240         $openidurl=~s!^http://http://!http://!;
1241         my $csr = create_openid_consumer($cgi,$forum);
1242         my $claimed_identity=$csr->claimed_identity($openidurl);
1243         if (!defined $claimed_identity) {
1244                 show_error($forum,"Указанная URL $openidurl не является OpenId");            
1245                 exit;
1246         }
1247         $cgi->param("openidvfy",1);
1248         $cgi->delete("user");
1249         $cgi->delete("openidsite");
1250         $cgi->delete("password");
1251         my $check_url = $claimed_identity->check_url(
1252                 return_to=> $cgi->url(-full=>1,-path_info=>1,-query=>1),
1253                 trust_root=> $cgi->url(-base=>1));
1254         print $cgi->redirect(-location=>$check_url);
1255         exit;
1256 }       
1257 #
1258 # Вызывается при редиректе от openid producer-а. Проверяет, что
1259 # удаленный сервер подтвердил openid и вызывает операцию для которой
1260 # (либо возврат на исходную страницу при операции login, либо постинг
1261 # реплики) 
1262 #
1263 sub openid_verify {
1264         my ($cgi,$forum) = @_;
1265         my $csr  = create_openid_consumer($cgi,$forum);
1266         if (my $setup_url = $csr->user_setup_url) {
1267                 print $cgi->redirect(-location=>$setup_url);
1268                 exit;
1269         } elsif ($csr->user_cancel) {
1270                 show_error($forum,"Ваш openid-сервер отказался подтвержать вашу
1271                 идентичность");
1272                 exit;
1273         } elsif (my $vident = $csr->verified_identity) {
1274                 #Успешная аутентификация.         
1275                 #Создаем сессию
1276                 my $user = $vident->url; 
1277                 # Remove trailing slash from URL if any
1278                 $user=~s/\/$//;
1279                 my %userbase;
1280                 dbmopen %userbase,datafile($forum,"passwd"),0664;
1281                 my $username = $user; 
1282                 $username =~ s/^http:\/\///;
1283                 if (!$userbase{$username}) {
1284                         $userbase{$username} = freeze($forum->{authenticated}={"openiduser"=>1});
1285                 } else {
1286                         $forum->{authenticated} = thaw ($userbase{$username});
1287                 }
1288                 dbmclose %userbase;
1289                 $forum->{"authenticated"}{"user"} = $username;
1290                 newsession(undef,$forum,$user);
1291                 # Если указан параметр reply, вызываем обработку реплики
1292                 if ($cgi->param("reply")) {     
1293                         reply("reply",$cgi,$forum);
1294                         exit;
1295                 }       
1296                 #Иначе, возвращаемся на исходную страницу
1297                 forum_redirect($cgi,$forum,undef);
1298         }       else {
1299                 show_error($forum,"Ошибка OpenId аутентификации");
1300                 exit;
1301         }       
1302 }
1303 #-----------------------------------------------------------------
1304 # Обработка форматированных текстовых полей
1305 #-----------------------------------------------------------------
1306
1307 sub input2tree {
1308         my ($cgi,$forum,$field_name) = @_;
1309         my $format = $cgi->param($field_name."_format");
1310         my $text = $cgi->param($field_name);
1311         if ($format eq "bbcode") {
1312                 my $parser = HTML::BBReverse->new(); 
1313                 $text="<div class=\"bbcode\">".$parser->parse($text)."</div>";
1314         } elsif ($format eq "text") {
1315                 $text=~s/\r?\n\r?\n/<\/p><p class=\"text\">/;
1316                 $text=~s/\r?\n/<br>/;
1317                 $text = "<div><p class=\"text\">".$text."</p></div>";
1318         } 
1319         my $txtree = str2tree($text);
1320         for my $badtag
1321         ("script","style","head","html","object","embed","iframe","frameset","frame",
1322         ($forum->{forbid_tags}?split(/\s*,\s*/,$forum->{forbid_tags}):())) {
1323                 for my $element ($txtree->find_by_tag_name($badtag)) {
1324                         $element->delete() if defined $element;
1325                 }       
1326         }       
1327         # Проверяем на наличие URL-ок не оформленных ссылками.
1328         return $txtree;
1329 }       
1330
1331
1332
1333 sub str2tree {
1334         my ($data)=@_;
1335         my $tree = HTML::TreeBuilder->new();
1336         # Set parser options here
1337         $tree->parse("<html><body><div>$data</div></body></html>");
1338         $tree->eof;
1339         my $element=$tree->find("body");
1340         while (($element =($element->content_list)[0])->tag ne "div") {
1341         }
1342         $element->detach;
1343         $tree->destroy;
1344         return $element;
1345 }       
1346
1347 sub tree2str {
1348         my ($tree)=@_;
1349         return $tree->as_HTML("<>&");
1350 }
1351
1352 #------------------------------------------------------------------------
1353 # Подстановка в дереве
1354 #------------------------------------------------------------------------
1355 # Находит 
1356 # элемент указанного класса и удаляет display: none из его атрибута
1357 # style. Возвращает 1, если элемент был раскрыт, и 0, если он и до этого 
1358 # был видимым.
1359 sub unhide_list {
1360         my ($tree,$class) = @_;
1361         my $msglist = $tree->look_down("class"=>$class);
1362         if ($msglist) {
1363                 my $style = $msglist->attr("style");
1364                 if ($style && $style =~ s/display: none;//) {
1365                         $msglist->attr("style",$style);
1366                         return 1;
1367                 } else {
1368                         return 0;
1369                 }       
1370         } 
1371 }       
1372 #
1373 # Находит первый элемент указанного класса, и приписывает ему display:
1374 # none в style.
1375 #
1376 sub hide_list {
1377         my ($tree,$class)=@_;
1378         my $msglist = $tree->look_down("class"=>$class);
1379         return undef unless $msglist;
1380         if (!$msglist->attr("style")) {
1381                 $msglist->attr("style","display: none;");
1382         } else {
1383                 my $style = $msglist->attr("style");
1384                 unless ($style=~ s/\bdisplay:\s+\w+\s*;/display: none;/) {
1385                         $style .= "display: none;";
1386                 } 
1387                 $msglist->attr("style",$style);
1388         }       
1389         return 1;
1390 }       
1391 #
1392 # Найти все элементы, удоволетворяющие заданному критерию и подставить в
1393 # них указанные атрибуты
1394
1395 # Параметры 1. Дерево (класса HTML::Element)
1396 # 2. Запрос - ссылка на список вида атрибут=>значение. 
1397 #    Этот список будет непосредственно передан в
1398 #    HTML::Element::look_down
1399 # 3. Далее пары имя-атрибута, значение. Если вместо имени атрибута
1400 #    использовать слово _content, заменено будет содержимое элемента.
1401 #    Значение для _content - ссылка на HTML::Element. Если там строка,
1402 #    она будет вставлена как одиночный текстовый узел.
1403 # 4. Возвращает число выполненных подстановок (0, если искомых элементов   
1404 #   не найдено.
1405 #
1406 sub substinfo {
1407         my ($tree,$query,@attrs) = @_;
1408         my $count;
1409         foreach my $element ($tree->look_down(@$query)) {
1410                 $count ++;
1411                 while (@attrs) {
1412                         my $attr = shift @attrs;
1413                         my $value = shift @attrs;
1414                         if ($attr eq "_content") {
1415                                 $element->delete_content;
1416                                 $element->push_content($value);
1417                         } else {        
1418                                 $element->attr($attr,$value);
1419                         }       
1420                 }       
1421         }
1422         return $count;  
1423 }
1424 #
1425 # newlistelement($tree,$elementclass,$listclass) 
1426 #
1427 # Если список с указанным классом скрыт, раскрывает его и возвращает 
1428 # (единственный) элемент 
1429 sub newlistelement {
1430         my ($tree,$element,$list) =@_;
1431         my $msglist = $tree->look_down("class"=>$list);
1432         if ($msglist) {
1433                 my $style = $msglist->attr("style");
1434                 if ($style && $style =~ s/display: none;//) {
1435                         $msglist->attr("style",$style);
1436                         return $msglist->look_down(class=>$element);
1437                 } else {
1438                         my $template = $msglist->look_down("class"=>$element);
1439                         return undef unless $template;
1440                         my $newitem=$template->clone;
1441                         $template->parent->push_content($newitem);
1442                         return $newitem;
1443                 }
1444         } else {
1445                 return undef;
1446         }
1447 }