licom.cgi: Assume all parameters to be in UTF-8.
[licom.git] / licom.cgi
index 80239b5..70398b2 100755 (executable)
--- a/licom.cgi
+++ b/licom.cgi
@@ -1,21 +1,39 @@
 #!/usr/bin/perl
 
+# LiCoM - Lightweight contact manager
+# Copyright (c) 2005-2006  Florian octo Forster <octo at verplant.org>
+#
+# This program is free software; you can redistribute it and/or modify it under
+# the terms of the GNU General Public License as published by the Free Software
+# Foundation; only version 2 of the License is applicable.
+#
+# This program is distributed in the hope that it will be useful, but WITHOUT
+# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
+# details.
+#
+# You should have received a copy of the GNU General Public License along with
+# this program; if not, write to the Free Software # Foundation, Inc.,
+# 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+
 use strict;
 use warnings;
 use lib (qw(lib));
 
+use Encode (qw(encode decode is_utf8));
 use CGI (':cgi');
 use CGI::Carp (qw(fatalsToBrowser));
 use URI::Escape;
-use Data::Dumper;
+use HTML::Entities (qw(encode_entities));
 
-use LiCoM::Config (qw(get_config));
-use LiCoM::Person;
+use LiCoM::Config (qw(get_config set_config read_config));
+use LiCoM::Connection ();
+use LiCoM::Group ();
+use LiCoM::Person ();
 
 our $Debug = 0;
-our $Config = {};
 
-our @MultiFields = (qw(address homephone cellphone officephone fax mail uri group));
+our @MultiFields = (qw(address homephone cellphone officephone fax mail uri));
 
 our %FieldNames = 
 (
@@ -31,7 +49,7 @@ our %FieldNames =
 
 our $MySelf = $ENV{'SCRIPT_NAME'};
 
-our $Action = param ('action');
+our $Action = param_utf8 ('action');
 $Action ||= 'default';
 
 our %Actions =
@@ -44,27 +62,32 @@ our %Actions =
        save    => [\&html_start, \&action_save,    \&html_end],
        search  => [\&html_start, \&action_search,  \&html_end],
        verify  => [\&html_start, \&action_verify,  \&html_end],
-       vcard   => \&action_vcard
+       delete  => [\&html_start, \&action_ask_del,  \&html_end],
+       expunge => [\&html_start, \&action_do_del,  \&html_end],
+       vcard   => \&action_vcard,
+       edit_group => [\&html_start, \&action_edit_group, \&html_end],
+       save_group => [\&html_start, \&action_save_group, \&html_end]
 );
 
-$Config = get_config ();
+read_config ();
 
 # make sure AuthLDAPRemoteUserIsDN is enabled.
 die unless ($ENV{'REMOTE_USER'});
-$Config->{'base_dn'} = $ENV{'REMOTE_USER'};
+#set_config ('base_dn', $ENV{'REMOTE_USER'});
 
-die unless (defined ($Config->{'uri'}) and defined ($Config->{'base_dn'})
-       and defined ($Config->{'bind_dn'}) and defined ($Config->{'password'}));
+die ("Configuration is incomplete") unless (defined (get_config ('uri'))
+       and defined (get_config ('base_dn'))
+       and defined (get_config ('bind_dn'))
+       and defined (get_config ('password')));
 
-LiCoM::Person->connect
+LiCoM::Connection->connect
 (
-       uri     => $Config->{'uri'},
-       base_dn => $Config->{'base_dn'},
-       bind_dn => $Config->{'bind_dn'},
-       password => $Config->{'password'}
-) or die;
+       uri      => get_config ('uri'),
+       bind_dn  => get_config ('bind_dn'),
+       password => get_config ('password')
+) or die ("Unable to connect to LDAP directory server " . get_config ('uri'));
 
-our ($UserCN, $UserID) = LiCoM::Person->get_user ($Config->{'base_dn'});
+our ($UserCN, $UserID) = LiCoM::Person->get_user ($ENV{'REMOTE_USER'});
 
 if (!$UserID and $Action ne 'save')
 {
@@ -73,12 +96,12 @@ if (!$UserID and $Action ne 'save')
 
 if (!$UserCN)
 {
-       die;
+       die ("No such user in the LDAP directory: " . $ENV{'REMOTE_USER'});
 }
 
 if (!defined ($Actions{$Action}))
 {
-       die;
+       die ("No such action: $Action");
 }
 
 if (ref ($Actions{$Action}) eq 'CODE')
@@ -93,7 +116,7 @@ elsif (ref ($Actions{$Action}) eq 'ARRAY')
        }
 }
 
-LiCoM::Person->disconnect ();
+LiCoM::Connection->disconnect ();
 
 exit (0);
 
@@ -101,106 +124,116 @@ exit (0);
 
 sub action_browse
 {
-       my $group = param ('group');
+       my $group = param_utf8 ('group');
        $group = shift if (@_);
        $group ||= '';
 
-       my @all;
-       if ($group)
-       {
-               @all = LiCoM::Person->search ([[group => $group]]);
-       }
-       else
-       {
-               @all = LiCoM::Person->search ();
-       }
-
        if (!$group)
        {
-               my @nogroup = ();
-               my %groups = ();
-               for (@all)
-               {
-                       my $person = $_;
-                       my @g = $person->get ('group');
-
-                       $groups{$_} = (defined ($groups{$_}) ? $groups{$_} + 1 : 1) for (@g);
-
-                       push (@nogroup, $person) if (!@g);
-               }
-               @all = @nogroup;
+               my @groups = LiCoM::Group->all ();
 
-               print qq(\t\t<h2>Contact Groups</h2>\n\t\t<ul class="groups">\n);
-               for (sort (keys (%groups)))
+               print qq(\t\t<h2>Contact groups</h2>\n\t\t<ul class="groups">\n);
+               for (@groups)
                {
                        my $group = $_;
-                       my $group_esc = uri_escape ($group);
-                       my $num = $groups{$group};
-
-                       print qq(\t\t\t<li><a href="$MySelf?action=browse&group=$group_esc">$group</a> ($num)</li>\n);
+                       my @members = $group->get_members ();
+                       my $members = scalar (@members);
+                       my $group_name = $group->name ();
+                       my $group_uri  = uri_escape_utf8 ($group_name);
+                       my $desc = $group->description ();
+
+                       print qq#\t\t\t<li><a href="$MySelf?action=browse&group=$group_uri">#,
+                       encode_entities ($group_name),
+                       qq#</a> ($members Member#, ($members == 1 ? ')' : 's)');
+                       print qq(<br />\n\t\t\t\t<span class="description">),
+                       encode_entities ($desc) . '</span>' if ($desc);
+                       print "</li>\n";
                }
-               if (!%groups)
+               if (!@groups)
                {
                        print qq(\t\t\t<li class="empty">There are no groups yet.</li>\n);
                }
-               print qq(\t\t</ul>\n\n);
-       }
-
-       if ($group)
-       {
-               print qq(\t\t<h2>Contact Group &quot;$group&quot;</h2>\n);
+               print <<EOF;
+               </ul>
+               <div class="menu">
+                       [<a href="$MySelf?action=list">List&nbsp;all</a>]
+               </div>
+EOF
        }
        else
        {
-               print qq(\t\t<h2>Contacts without a group</h2>\n);
-       }
-
-       print qq(\t\t<ul class="results">\n);
-       for (sort { $a->name () cmp $b->name () } (@all))
-       {
-               my $person = $_;
-               my $cn = $person->name ();
-               my $cn_esc = uri_escape ($cn);
-
-               print qq(\t\t\t<li><a href="$MySelf?action=detail&cn=$cn_esc">$cn</a></li>\n);
-       }
-       if (!@all)
-       {
-               print "\t\t\t<li>There are no matching entries.</li>\n";
-       }
-       print qq(\t\t</ul>\n\n);
+               my $group_obj    = LiCoM::Group->load ($group);
+               my $group_uri    = uri_escape_utf8 ($group_obj->name ());
+               my $group_html   = encode_entities ($group_obj->name ());
+               my @member_names = $group_obj->get_members ();
+               my $desc         = $group_obj->description ();
+               my $desc_html    = encode_entities ($desc || '');
+               
+               print qq(\t\t<h2>Contact group &quot;$group_html&quot;</h2>\n);
+               print qq(\t\t<div>$desc_html</div>\n) if ($desc);
+               print qq(\t\t<ul class="results">\n);
+               for (sort (@member_names))
+               {
+                       my $cn = $_;
+                       my $cn_uri  = uri_escape_utf8 ($cn);
+                       my $cn_html = encode_entities ($cn);
 
-       print qq(\t\t<div class="menu">\n);
-       if ($group)
-       {
-               my $group_esc = uri_escape ($group);
-               print qq(\t\t\t[<a href="$MySelf?action=list&group=$group_esc">List</a>]\n),
-               qq(\t\t\t[<a href="$MySelf?action=browse">Back</a>]\n);
-       }
-       else
-       {
-               print qq(\t\t\t[<a href="$MySelf?action=list">List</a>]\n);
+                       print qq(\t\t\t<li><a href="$MySelf?action=detail&cn=$cn_uri">$cn_html</a></li>\n);
+               }
+               
+               print <<EOF;
+               </ul>
+               <div class="menu">
+                       [<a href="$MySelf?action=list&group=$group_uri">List</a>]
+                       [<a href="$MySelf?action=browse">Back</a>]
+                       [<a href="$MySelf?action=edit_group&group=$group_uri">Edit</a>]
+               </div>
+EOF
        }
-       print qq(\t\t</div>\n);
 }
 
 sub action_list
 {
-       my $group = param ('group');
-       $group = shift if (@_);
-       $group ||= '';
+       my $group_name = param_utf8 ('group');
+       $group_name = shift if (@_);
+       $group_name ||= '';
+
+       my $group_name_html = encode_entities ($group_name || '');
 
-       my $title = $group ? "List of group &quot;$group&quot;" : 'List of all addresses';
+       my $title = $group_name
+               ? "List of group &quot;$group_name_html&quot;"
+               : 'List of all addresses';
        my @fields = (qw(address homephone cellphone officephone fax mail));
 
        my @all = ();
-       if ($group)
+       if ($group_name)
        {
-               @all = LiCoM::Person->search ([[group => $group]]);
+               my $group_obj = LiCoM::Group->load ($group_name);
+               if (!$group_obj)
+               {
+                       print <<HTML;
+               <div class="error">
+                       Unable to load group &quot;$group_name_html&quot;.
+               </div>
+HTML
+                       return;
+               }
+               for ($group_obj->get_members ())
+               {
+                       my $cn = $_;
+                       my $person_obj = LiCoM::Person->load ($cn);
+
+                       if (!$person_obj)
+                       {
+                               print STDERR "Unable to load cn = $cn;\n";
+                               next;
+                       }
+                       push (@all, $person_obj);
+               }
        }
        else
        {
-               @all = LiCoM::Person->search ();
+               @all = LiCoM::Person->search ([[group => $group_name]]);
        }
 
        print <<EOF;
@@ -219,26 +252,30 @@ EOF
        for (sort { $a->name () cmp $b->name () } (@all))
        {
                my $person = $_;
+               my $cn = $person->name ();
                my $sn = $person->lastname ();
                my $gn = $person->firstname ();
 
+               my $cn_uri  = uri_escape_utf8 ($cn);
+               my $cn_html = encode_entities ("$sn, $gn");
+
                print "\t\t\t<tr>\n",
-               "\t\t\t\t<td>$sn, $gn</td>\n";
+               qq(\t\t\t\t<td><a href="$MySelf?action=detail&cn=$cn_uri">$cn_html</a></td>\n);
 
                for (@fields)
                {
                        my $field = $_;
                        my @values = $person->get ($field);
-                       print "\t\t\t\t<td>" . join ('<br />', @values) . "</td>\n";
+                       print "\t\t\t\t<td>" . join ('<br />', map { markup_field ($field, $_) } (@values)) . "</td>\n";
                }
 
                print "\t\t\t</tr>\n";
        }
        print "\t\t</table>\n\n";
 
-       if ($group)
+       if ($group_name)
        {
-               my $group_esc = uri_escape ($group);
+               my $group_esc = uri_escape_utf8 ($group_name);
                print qq(\t\t<div class="menu">[<a href="$MySelf?action=browse&group=$group_esc">Back</a>]</div>\n);
        }
        else
@@ -249,26 +286,27 @@ EOF
 
 sub action_detail
 {
-       my $cn = param ('cn');
+       my $cn = param_utf8 ('cn');
        $cn = shift if (@_);
        die unless ($cn);
 
+       my $cn_html = encode_entities ($cn);
+       my $cn_uri  = uri_escape_utf8 ($cn);
+
        my $person = LiCoM::Person->load ($cn);
        if (!$person)
        {
-               print qq(\t<div>Entry &quot;$cn&quot; could not be loaded from DB.</div>\n);
+               print qq(\t<div>Entry &quot;$cn_html&quot; could not be loaded from DB.</div>\n);
                return;
        }
 
-       print qq(\t\t<h2>Details for $cn</h2>\n);
-
-       my $cn_esc = uri_escape ($cn);
+       print qq(\t\t<h2>Details for $cn_html</h2>\n);
 
        print <<EOF;
                <table class="detail">
                        <tr>
                                <th>Name</th>
-                               <td>$cn</td>
+                               <td>$cn_html</td>
                        </tr>
 EOF
        for (@MultiFields)
@@ -276,52 +314,59 @@ EOF
                my $field = $_;
                my $values = $person->get ($field);
                my $num = scalar (@$values);
-               my $print = defined ($FieldNames{$field}) ? $FieldNames{$field} : $field;
+               my $field_name = defined ($FieldNames{$field}) ? $FieldNames{$field} : $field;
 
                next unless ($num);
 
+               $field_name = encode_entities ($field_name);
+
                print "\t\t\t<tr>\n";
                if ($num > 1)
                {
-                       print qq(\t\t\t\t<th rowspan="$num">$print</th>\n);
+                       print qq(\t\t\t\t<th rowspan="$num">$field_name</th>\n);
                }
                else
                {
-                       print qq(\t\t\t\t<th>$print</th>\n);
+                       print qq(\t\t\t\t<th>$field_name</th>\n);
                }
 
                for (my $i = 0; $i < $num; $i++)
                {
-                       my $val = $values->[$i];
-
-                       if ($field eq 'group')
-                       {
-                               my $val_esc = uri_escape ($val);
-                               $val = qq(<a href="$MySelf?action=browse&group=$val_esc">$val</a>);
-                       }
-                       elsif ($field eq 'uri')
-                       {
-                               my $uri = $val;
-                               $uri = qq(http://$val) unless ($val =~ m#^[a-z]+://#);
-                               $val = qq(<a href="$uri" class="extern">$val</a>);
-                       }
-                       elsif ($field eq 'mail')
-                       {
-                               $val = qq(<a href="mailto:$val" class="mail">$val</a>);
-                       }
+                       my $val = markup_field ($field, $values->[$i]);
                        
                        print "\t\t\t<tr>\n" if ($i);
                        print "\t\t\t\t<td>$val</td>\n",
                        "\t\t\t</tr>\n";
                }
        }
+
+       my @groups = LiCoM::Group->load_by_member ($cn);
+       if (@groups)
+       {
+               my $num = scalar (@groups);
+               print "\t\t\t<tr>\n",
+               "\t\t\t\t<th", ($num == 1 ? '' : qq( rowspan="$num")), ">Group", ($num == 1 ? '' : 's'), "</th>\n";
+               for (my $i = 0; $i < $num; $i++)
+               {
+                       my $group = $groups[$i];
+                       my $group_name = $group->name ();
+                       my $group_uri  = uri_escape_utf8 ($group_name);
+                       my $group_html = encode_entities ($group_name);
+
+                       print "\t\t\t<tr>\n" if ($i != 0);
+                       print qq(\t\t\t\t<td><a href="$MySelf?action=browse&group=$group_uri">$group_html</a></td>\n),
+                       "\t\t\t</tr>\n";
+               }
+       }
+       
        print <<EOF;
                </table>
 
                <div class="menu">
-                       [<a href="$MySelf?action=verify&cn=$cn_esc">Verify</a>]
-                       [<a href="$MySelf?action=vcard&cn=$cn_esc">vCard</a>]
-                       [<a href="$MySelf?action=edit&cn=$cn_esc">Edit</a>]
+                       [<a href="$MySelf?action=verify&cn=$cn_uri">Verify</a>]
+                       [<a href="$MySelf?action=vcard&cn=$cn_uri">vCard</a>]
+                       [<a href="$MySelf?action=edit&cn=$cn_uri">Edit</a>]
+                       [<a href="$MySelf?action=delete&cn=$cn_uri">Delete</a>]
                </div>
 
 EOF
@@ -329,7 +374,7 @@ EOF
 
 sub action_search
 {
-       my $search = param ('search');
+       my $search = param_utf8 ('search');
 
        $search ||= '';
        $search =~ s/[^\s\w]//g;
@@ -371,9 +416,10 @@ sub action_search
        {
                my $person = $_;
                my $cn = $person->name ();
-               my $cn_esc = uri_escape ($cn);
+               my $cn_uri  = uri_escape_utf8 ($cn);
+               my $cn_html = encode_entities ($cn);
 
-               print qq(\t\t<li><a href="$MySelf?action=detail&cn=$cn_esc">$cn</a></li>\n);
+               print qq(\t\t<li><a href="$MySelf?action=detail&cn=$cn_uri">$cn_html</a></li>\n);
        }
        print qq(\t</ul>\n);
 }
@@ -382,11 +428,13 @@ sub action_edit
 {
        my %opts = @_;
 
-       my $cn = param ('cn');
+       my $cn = param_utf8 ('cn');
 
        $cn = $opts{'cn'} if (defined ($opts{'cn'}));
        $cn ||= '';
 
+       my $cn_html = encode_entities ($cn);
+
        if (!$UserID)
        {
                $cn = $UserCN;
@@ -397,6 +445,9 @@ sub action_edit
        my $lastname;
        my $firstname;
 
+       my $lastname_html;
+       my $firstname_html;
+
        my $contacts = {};
        $contacts->{$_} = [] for (@MultiFields);
 
@@ -419,13 +470,16 @@ sub action_edit
                }
        }
 
-       $lastname    = param ('lastname')    if (param ('lastname')  and $UserID);
-       $firstname   = param ('firstname')   if (param ('firstname') and $UserID);
+       $lastname  = param_utf8 ('lastname')  if (param_utf8 ('lastname')  and $UserID);
+       $firstname = param_utf8 ('firstname') if (param_utf8 ('firstname') and $UserID);
 
        get_contacts ($contacts);
        
        $lastname    =   $opts{'lastname'}     if (defined ($opts{'lastname'}));
        $firstname   =   $opts{'firstname'}    if (defined ($opts{'firstname'}));
+       $lastname_html  = encode_entities ($lastname);
+       $firstname_html = encode_entities ($firstname);
+
        for (@MultiFields)
        {
                my $field = $_;
@@ -434,7 +488,7 @@ sub action_edit
 
        if ($cn)
        {
-               print "\t\t<h2>Edit contact $cn</h2>\n";
+               print "\t\t<h2>Edit contact $cn_html</h2>\n";
        }
        else
        {
@@ -442,20 +496,20 @@ sub action_edit
        }
 
        print <<EOF;
-               <form action="$MySelf" method="post">
+               <form action="$MySelf" method="post" accept-charset="UTF-8">
                <input type="hidden" name="action" value="save" />
-               <input type="hidden" name="cn" value="$cn" />
+               <input type="hidden" name="cn" value="$cn_html" />
                <table class="edit">
                        <tr>
                                <th>Lastname</th>
 EOF
        if ($UserID)
        {
-               print qq(\t\t\t\t<td><input type="text" name="lastname" value="$lastname" /></td>\n);
+               print qq(\t\t\t\t<td><input type="text" name="lastname" value="$lastname_html" /></td>\n);
        }
        else
        {
-               print qq(\t\t\t\t<td>$lastname</td>\n);
+               print qq(\t\t\t\t<td>$lastname_html</td>\n);
        }
        print <<EOF;
                        </tr>
@@ -464,11 +518,11 @@ EOF
 EOF
        if ($UserID)
        {
-               print qq(\t\t\t\t<td><input type="text" name="firstname" value="$firstname" /></td>\n);
+               print qq(\t\t\t\t<td><input type="text" name="firstname" value="$firstname_html" /></td>\n);
        }
        else
        {
-               print qq(\t\t\t\t<td>$firstname</td>\n);
+               print qq(\t\t\t\t<td>$firstname_html</td>\n);
        }
        
        print "\t\t\t</tr>\n";
@@ -479,13 +533,16 @@ EOF
                my $print = defined ($FieldNames{$field}) ? $FieldNames{$field} : $field;
                my @values = @{$contacts->{$field}};
 
-               next if (!$UserID and $field eq 'group');
+               next if ($field eq 'group');
 
                push (@values, '');
+
+               $field = encode_entities ($field);
+               $print = encode_entities ($print);
                
                for (@values)
                {
-                       my $value = $_;
+                       my $value = encode_entities ($_);
 
                        print <<EOF;
                        <tr>
@@ -496,6 +553,39 @@ EOF
                }
        }
 
+       if ($UserID)
+       {
+               my @all_groups = LiCoM::Group->all ();
+
+               if (@all_groups)
+               {
+                       print "\t\t\t<tr>\n",
+                       "\t\t\t\t<th>Group(s)</th>\n",
+                       qq(\t\t\t\t<td><select name="group" multiple="multiple" size="5">\n);
+
+                       for (@all_groups)
+                       {
+                               my $group = $_;
+                               my $group_name = encode_entities ($group->name ());
+                               my $selected = '';
+
+                               if (grep { $cn eq $_ } ($group->get_members ()))
+                               {
+                                       $selected = ' selected="selected"';
+                               }
+
+                               print qq(\t\t\t\t\t<option value="$group_name"$selected>$group_name</option>\n);
+                       }
+                       print "\t\t\t\t</select></td>\n",
+                       "\t\t\t</tr>\n";
+               }
+                       
+               print "\t\t\t<tr>\n",
+               "\t\t\t\t<th>New Group</th>\n",
+               qq(\t\t\t\t<td><input type="text" name="newgroup" value="" /></td>\n),
+               "\t\t\t</tr>\n";
+       }
+
        print <<EOF;
                        <tr>
                                <th colspan="2" class="menu">
@@ -518,7 +608,7 @@ EOF
 
 sub action_save
 {
-       my $cn = $UserID ? param ('cn') : $UserCN;
+       my $cn = $UserID ? param_utf8 ('cn') : $UserCN;
 
        if (verify_fields ())
        {
@@ -534,7 +624,7 @@ sub action_save
 
        die unless ($UserID);
 
-       my $button = lc (param ('button'));
+       my $button = lc (param_utf8 ('button'));
        $button ||= 'save';
 
        if ($button eq 'cancel')
@@ -543,15 +633,15 @@ sub action_save
                return;
        }
 
-       if (!param ('lastname') or !param ('firstname'))
+       if (!param_utf8 ('lastname') or !param_utf8 ('firstname'))
        {
                print qq(\t<div class="error">You have to give both, first and lastname, to identify this record.</div>\n);
                action_edit (cn => '');
                return;
        }
 
-       my $lastname  = param ('lastname');
-       my $firstname = param ('firstname');
+       my $lastname  = param_utf8 ('lastname');
+       my $firstname = param_utf8 ('firstname');
 
        my $contacts = get_contacts ();
 
@@ -565,6 +655,29 @@ sub action_save
        
        $cn = $person->name ();
 
+       for (param_utf8 ('group'))
+       {
+               my $group_name = $_;
+               my $group = LiCoM::Group->load ($group_name);
+
+               if ($group)
+               {
+                       $group->add_members ($cn);
+               }
+               else
+               {
+                       my $group_html = encode_entities ($group_name);
+                       print qq(\t<div class="error">Group &quot;$group_html&quot; does not exist or could not be loaded.</div>\n);
+               }
+       }
+
+       if (param_utf8 ('newgroup'))
+       {
+               # FIXME add error handling
+               my $group_name = param_utf8 ('newgroup');
+               LiCoM::Group->create ($group_name, '', $cn);
+       }
+
        if ($button eq 'apply')
        {
                action_edit (cn => $cn);
@@ -577,12 +690,12 @@ sub action_save
 
 sub action_update
 {
-       my $cn = $UserID ? param ('cn') : $UserCN;
-       my $person = LiCoM::Person->load ($cn);
+       my $cn = $UserID ? param_utf8 ('cn') : $UserCN;
 
-       die unless ($person);
+       my $person = LiCoM::Person->load ($cn);
+       die ("Unable to load CN `$cn'") unless ($person);
 
-       my $button = lc (param ('button'));
+       my $button = lc (param_utf8 ('button'));
        $button ||= 'save';
 
        if ($UserID and $button eq 'cancel')
@@ -593,13 +706,39 @@ sub action_update
 
        if ($UserID)
        {
-               my $lastname  = param ('lastname');
-               my $firstname = param ('firstname');
+               my $lastname  = param_utf8 ('lastname');
+               my $firstname = param_utf8 ('firstname');
+
+               my $old_cn = $person->name ();
+
+               print <<HTML;
+<div><code>
+       \$lastname = $lastname<br />
+       \$firstname = $firstname<br />
+       \$old_cn = $old_cn
+</code></div>
+HTML
 
                $person->lastname  ($lastname)  if ($lastname  and $lastname  ne $person->lastname ());
                $person->firstname ($firstname) if ($firstname and $firstname ne $person->firstname ());
 
                $cn = $person->name ();
+
+               # Change the cn's saved in the groups
+               if ($old_cn ne $cn)
+               {
+                       my @groups = LiCoM::Group->load_by_member ($old_cn);
+                       for (@groups)
+                       {
+                               # ->del_members automatically deleted the
+                               # group, if no more members exist. So this
+                               # order is important.
+                               print "<div><code>\$cn = " . encode_entities ($cn) . "; "
+                               . "\$old_cn = " . encode_entities ($old_cn) . ";</code></div>\n";
+                               $_->add_members ($cn);
+                               $_->del_members ($old_cn);
+                       }
+               } # if ($old_cn ne $cn)
        }
 
        my $contacts = get_contacts ();
@@ -621,6 +760,51 @@ sub action_update
                }
        }
 
+       # only `authorized' users may see and change groups
+       if ($UserID)
+       {
+               my %changed_groups = map { $_ => 1 } (param_utf8 ('group'));
+               my @current_groups = LiCoM::Group->load_by_member ($cn);
+
+               for (@current_groups)
+               {
+                       my $group_obj = $_;
+                       my $group_name = $group_obj->name ();
+
+                       if (!defined ($changed_groups{$group_name}))
+                       {
+                               $group_obj->del_members ($cn);
+                       }
+                       else
+                       {
+                               delete ($changed_groups{$group_name});
+                       }
+               }
+               for (keys %changed_groups)
+               {
+                       my $group_name = $_;
+                       my $group_obj = LiCoM::Group->load ($group_name) or die;
+
+                       $group_obj->add_members ($cn);
+               }
+
+               if (param_utf8 ('newgroup'))
+               {
+                       # FIXME add error handling
+                       my $group_name = param_utf8 ('newgroup');
+                       LiCoM::Group->create ($group_name, '', $cn);
+               }
+       }
+
+       if (!$UserID)
+       {
+               print <<HTML;
+               <h3>Your changes have been saved.</h3>
+               <p>Thank you very much for taking the time to keep this record up to date.</p>
+
+HTML
+       }
+
        if ($button eq 'apply' or !$UserID)
        {
                action_edit (cn => $cn);
@@ -633,7 +817,7 @@ sub action_update
 
 sub action_vcard
 {
-       my $cn = param ('cn');
+       my $cn = param_utf8 ('cn');
        $cn = shift if (@_);
        die unless ($cn);
 
@@ -653,7 +837,7 @@ sub action_vcard
 
        my $sn = $person->lastname ();
        my $gn = $person->firstname ();
-       my $cn_esc = uri_escape ($cn);
+       my $cn_esc = uri_escape_utf8 ($cn);
 
        print <<EOF;
 Content-Type: text/x-vcard
@@ -671,6 +855,8 @@ EOF
                my $vc_fld = $vcard_types{$field};
                my $values = $person->get ($field);
 
+               next unless ($vc_fld);
+
                for (@$values)
                {
                        my $value = $_;
@@ -682,10 +868,12 @@ EOF
 
 sub action_verify
 {
-       my $cn = param ('cn');
+       my $cn = param_utf8 ('cn');
        $cn = shift if (@_);
        die unless ($cn);
 
+       my $cn_html = encode_entities ($cn);
+
        my $person = LiCoM::Person->load ($cn);
        die unless ($person);
 
@@ -693,21 +881,24 @@ sub action_verify
        $mail ||= '';
 
        my $message;
-       my $password = $person->password ();
+       my ($password) = $person->get ('password');
+       my $password_html;
 
        if (!$password)
        {
                $password = pwgen ();
-               $person->password ($password);
+               $person->set ('password', [$password]);
        }
+       $password_html = encode_entities ($password);
 
-       $message = qq(The password for the record &quot;$cn&quot; is &quot;$password&quot;.);
+       $message = qq(The password for the record &quot;$cn_html&quot; is &quot;$password_html&quot;.);
 
        if ($mail)
        {
                if (action_verify_send_mail ($person))
                {
-                       $message .= qq( A request for verification has been sent to $mail.);
+                       my $mail_html = encode_entities ($mail);
+                       $message .= qq( A request for verification has been sent to $mail_html.);
                }
        }
        else
@@ -729,8 +920,8 @@ sub action_verify_send_mail
        my ($owner_mail) = $owner->get ('mail');
        if (!$owner_mail)
        {
-               my $cn = uri_escape ($UserCN);
-               print qq(\t\t<div class="error">You have no email set in your own profile. <a href="$MySelf?action=edit&cn=$cn">Edit it now</a>!</div>\n);
+               my $cn_uri = uri_escape_utf8 ($UserCN);
+               print qq(\t\t<div class="error">You have no email set in your own profile. <a href="$MySelf?action=edit&cn=$cn_uri">Edit it now</a>!</div>\n);
                return (0);
        }
 
@@ -741,15 +932,15 @@ sub action_verify_send_mail
        }
        $max_width++;
 
-       my $person_name = $person->name ();
+       my $person_name   = $person->name ();
        my ($person_mail) = $person->get ('mail');
-       my $person_gn = $person->firstname ();
-       my $password = $person->password ();
+       my $person_gn     = $person->firstname ();
+       my ($password)    = $person->get ('password');
 
        my $host = $ENV{'HTTP_HOST'};
-       my $url = 'http://' . $host . $MySelf;
+       my $url = (defined ($ENV{'HTTPS'}) ? 'https://' : 'http://') . $host . $MySelf;
        
-       open ($smh, "| /usr/sbin/sendmail -t -f $owner_mail") or die ("open pipe to sendmail: $!");
+       open ($smh, '|-', '/usr/sbin/sendmail', '-t', '-f', $owner_mail) or die ("open (sendmail): $!");
        print $smh <<EOM;
 To: $person_name <$person_mail>
 From: $UserCN <$owner_mail>
@@ -773,23 +964,137 @@ EOM
        print $smh <<EOM;
 
 If this entry is outdated or incomplete, please take a minute and correct it.
-  Address:  $url
+  Address: $url
  Username: $person_name
  Password: $password
 
-Thank you very much :) Regards,
+Thank you very much :)
+
+Regards,
 $UserCN
+--
+This message was automatically generated by LiCoM,
+http://verplant.org/licom/
 EOM
        close ($smh);
 
        return (1);
 }
 
+sub action_ask_del
+{
+       my $cn = param_utf8 ('cn');
+       $cn or die;
+
+       my $person = LiCoM::Person->load ($cn);
+       $person or die;
+
+       my $cn_uri  = uri_escape_utf8 ($cn);
+       my $cn_html = encode_entities ($cn);
+
+       print <<EOF;
+               <h2>Really delete $cn_html?</h2>
+
+               <div>
+                       You are about to delete <strong>$cn_html</strong>.
+                       Are you totally, absolutely sure you want to do this?
+               </div>
+
+               <div class="menu">
+                       [<a href="$MySelf?action=expunge&cn=$cn_uri">Yes, delete</a>]
+                       [<a href="$MySelf?action=detail&cn=$cn_uri">No, keep</a>]
+               </div>
+
+EOF
+}
+
+sub action_do_del
+{
+       my $cn = param_utf8 ('cn');
+       $cn or die;
+
+       my $cn_html = encode_entities ($cn);
+
+       my $person = LiCoM::Person->load ($cn);
+       $person or die;
+
+       $person->delete ();
+
+       print <<EOF;
+               <div>$cn_html has been deleted.</div>
+
+EOF
+       action_browse ();
+}
+
+sub action_edit_group
+{
+       my $group_name = param_utf8 ('group') or die;
+
+       my $group_name_html = encode_entities ($group_name);
+
+       my $group_obj = LiCoM::Group->load ($group_name);
+
+       if (!$group_obj)
+       {
+               print qq(\t<div class="error">Group &quot;$group_name_html&quot; does not exist or could not be loaded.</div>\n);
+               return;
+       }
+
+       $group_name_html = encode_entities ($group_obj->name ());
+
+       my $desc_html = encode_entities ($group_obj->description () || '');
+
+       print <<HTML;
+       <h2>Edit contact group &quot;$group_name_html&quot;</h2>
+       <form action="$MySelf" method="post" accept-charset="UTF-8">
+         <input type="hidden" name="action" value="save_group" />
+         <input type="hidden" name="group" value="$group_name_html" />
+         <table>
+           <tr>
+             <th>Group Name</th>
+             <td>$group_name_html</td>
+           </tr>
+           <tr>
+             <th>Description</th>
+             <td><input type="text" name="description" value="$desc_html" /></td>
+           </tr>
+           <tr>
+             <th colspan="2"><input type="submit" name="button" value="Save" /></th>
+           </tr>
+         </table>
+       </form>
+HTML
+}
+
+sub action_save_group
+{
+       my $group_name = param_utf8 ('group') or die;
+
+       my $group_name_html = encode_entities ($group_name);
+
+       my $group_obj = LiCoM::Group->load ($group_name);
+
+       if (!$group_obj)
+       {
+               print qq(\t<div class="error">Group &quot;$group_name_html&quot; does not exist or could not be loaded.</div>\n);
+               return;
+       }
+
+       my $desc = param_utf8 ('description');
+       $group_obj->description ($desc);
+
+       action_browse ();
+       return;
+}
+
 sub html_start
 {
        my $title = shift;
        $title = q(Lightweight Contact Manager) unless ($title);
 
+       $title = encode_entities ($title);
+
        print <<EOF;
 Content-Type: text/html; charset=UTF-8
 
@@ -909,6 +1214,7 @@ Content-Type: text/html; charset=UTF-8
                        table.list
                        {
                                width: 100%;
+                               border: 2px solid #d0d0d0;
                        }
 
                        table.list td
@@ -919,18 +1225,23 @@ Content-Type: text/html; charset=UTF-8
                        td
                        {
                                color: black;
-                               background-color: #cccccc;
+                               background-color: #e8e8e8;
                                vertical-align: top;
                        }
 
                        th
                        {
                                color: black;
-                               background-color: #999999;
+                               background-color: #d0d0d0;
                                padding: 0.3ex;
                                text-align: left;
                                vertical-align: top;
                        }
+
+                       ul.groups li
+                       {
+                               margin-top: 0.5ex;
+                       }
                }
 
                \@media print
@@ -1001,21 +1312,23 @@ Content-Type: text/html; charset=UTF-8
 
        <body>
 EOF
+
        if ($UserID)
        {
-               my $search = param ('search') || '';
+               my $search = param_utf8 ('search') || '';
+               $search = encode_entities ($search);
                print <<EOF;
                <div class="topmenu">
-                       <form action="$MySelf" method="post">
+                       <form action="$MySelf" method="post" accept-charset="UTF-8">
                                <input type="hidden" name="action" value="browse" />
                                <input type="submit" name="button" value="Browse" />
                        </form>
-                       <form action="$MySelf" method="post">
+                       <form action="$MySelf" method="post" accept-charset="UTF-8">
                                <input type="hidden" name="action" value="search" />
                                <input type="text" name="search" value="$search" />
                                <input type="submit" name="button" value="Search" />
                        </form>
-                       <form action="$MySelf" method="post">
+                       <form action="$MySelf" method="post" accept-charset="UTF-8">
                                <input type="hidden" name="action" value="edit" />
                                <input type="hidden" name="dn" value="" />
                                <input type="submit" name="button" value="Add New" />
@@ -1031,7 +1344,7 @@ sub html_end
        print <<EOF;
                <div class="foot">
                        &quot;Lightweight Contact Manager&quot;,
-                       written 2005 by <a href="http://verplant.org/">Florian octo Forster</a>
+                       written 2005-2006 by <a href="http://verplant.org/">Florian octo Forster</a>
                        &lt;octo at verplant.org&gt;
                </div>
        </body>
@@ -1082,7 +1395,7 @@ sub pwgen
 sub verify_fields
 {
        my @errors = ();
-       for (param ('uri'))
+       for (param_utf8 ('uri'))
        {
                my $val = $_;
                next unless ($val);
@@ -1094,14 +1407,14 @@ sub verify_fields
                }
        }
 
-       for (param ('homephone'), param ('cellphone'), param ('officephone'), param ('fax'))
+       for (param_utf8 ('homephone'), param_utf8 ('cellphone'), param_utf8 ('officephone'), param_utf8 ('fax'))
        {
                my $number = $_;
                next unless ($number);
 
-               if ($number !~ m/^\+/)
+               if ($number !~ m/^\+[0-9 \-]+$/)
                {
-                       push (@errors, 'Telephone numbers have to begin with the country code, e.g. &quot;+49 911 123456&quot;');
+                       push (@errors, 'Telephone numbers have to begin with the country code and only numbers, spaces and dashes are allowed, e.g. &quot;+49 911-123456&quot;');
                        last;
                }
        }
@@ -1119,6 +1432,37 @@ sub verify_fields
        return (scalar (@errors));
 }
 
+sub markup_field
+{
+       my $field = shift;
+       my $value = shift;
+
+       my $value_uri  = uri_escape_utf8 ($value);
+       my $value_html = encode_entities ($value);
+
+       if ($field eq 'group')
+       {
+               return (qq(<a href="$MySelf?action=browse&group=$value_uri">$value_html</a>));
+       }
+       elsif ($field eq 'uri')
+       {
+               if ($value =~ m#^([a-z]+)://(.+)$#)
+               {
+                       $value_uri = $1 . '://' . uri_escape_utf8 ($2);
+               }
+               else
+               {
+                       $value_uri = 'http://' . uri_escape_utf8 ($value);
+               }
+               return (qq(<a href="$value_uri" class="extern">$value_html</a>));
+       }
+       elsif ($field eq 'mail')
+       {
+               return (qq(<a href="mailto:$value_uri" class="mail">$value_html</a>));
+       }
+       return ($value_html);
+}
+
 sub get_contacts
 {
        my $contacts = @_ ? shift : {};
@@ -1126,7 +1470,7 @@ sub get_contacts
        for (@MultiFields)
        {
                my $field = $_;
-               my @values = grep { $_ } (param ($field));
+               my @values = grep { $_ } (param_utf8 ($field));
 
                next unless (@values);
 
@@ -1134,8 +1478,8 @@ sub get_contacts
                {
                        for (@values)
                        {
-                               $_ =~ s/\D//g;
-                               $_ = '+' . $_;
+                               $_ =~ s/[^0-9 \-]//g;
+                               $_ = '+' . $_ if ($_);
                        }
                }
                
@@ -1144,3 +1488,35 @@ sub get_contacts
 
        return ($contacts);
 }
+
+sub is_valid_utf8
+{
+       my $str = join ('', @_);
+
+       # Taken from here: <http://www.w3.org/International/questions/qa-forms-utf-8>
+       return ($str =~ m/^(
+     [\x09\x0A\x0D\x20-\x7E]            # ASCII
+   | [\xC2-\xDF][\x80-\xBF]             # non-overlong 2-byte
+   |  \xE0[\xA0-\xBF][\x80-\xBF]        # excluding overlongs
+   | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2}  # straight 3-byte
+   |  \xED[\x80-\x9F][\x80-\xBF]        # excluding surrogates
+   |  \xF0[\x90-\xBF][\x80-\xBF]{2}     # planes 1-3
+   | [\xF1-\xF3][\x80-\xBF]{3}          # planes 4-15
+   |  \xF4[\x80-\x8F][\x80-\xBF]{2}     # plane 16
+  )*$/x);
+}
+
+sub param_utf8
+{
+       my @args = @_;
+       my @ret = ();
+
+       @ret = grep { is_valid_utf8 ($_) } (param (@args));
+       $_ = decode ('UTF-8', $_) for (@ret);
+       return (wantarray () ? @ret : $ret[0]);
+}
+
+sub uri_escape_utf8
+{
+       return (uri_escape (encode ('UTF-8', shift)));
+}