# $Id: LiveJournal.pm,v 1.5 2001/03/22 21:37:47 archon Exp $

package LiveJournal::Friend;

use strict;
use Carp;

@LiveJournal::Friend::ISA = qw/LiveJournal/;

sub check {
	my ($self) = shift;
	my $content = $self->_new_modeline('checkfriends');
	$content .= "&lastupdate=" . $self->lastupdate();
	my $response = $self->_send_mode($content);
	if ($response) {
		my $hash = {split("\n", $response->{'_content'})};
		if ($hash->{'success'} eq "OK") {
			$self->lastupdate($hash->{'lastupdate'});
		}
		return $hash;
	} else {
		return undef;
	}
}

sub getgroups {
	my ($self) = shift;
	my $content = $self->_new_modeline('getfriendgroups');
	my $response = $self->_send_mode($content);
	if ($response) {
		return {split("\n", $response->{_content})};
	} else {
		return undef;
	}
}

sub friends_by_group {
	my ($self) = shift;

	my %ret;
	for my $friend (@{$self->friends()}) {
		if (exists ($friend->{'groupmask'})) {
			$ret{$friend->{'user'}} = [grep { $friend->{'groupmask'} & (2 ** $_)}
			1 .. $self->friend_group_max()];
		}
	}
	return \%ret;
}

sub add_friend_to_group {
	my ($self, $user, $group) = @_;
	my ($response);
	if (defined ($user) and exists $self->{'_friend_group'}->{$group}) {
		foreach my $friend (@{$self->friends()}) {
			if ($friend->{'user'} eq $user) {
				my $oldmask = $friend->{'groupmask'}
					? $friend->{'groupmask'}
					: 1;
				my $newmask = $oldmask ^ (1 << $group);
				if ($newmask < $oldmask) {
					carp ("$user is already in group $group");
					return undef;
				}
				$response = $self->editgroups({$group => {$user => $newmask}});
				last;
			}
		}
	}
	return $response;
}

sub remove_friend_from_group {
	my ($self, $user, $group) = @_;
	my $response;
	if (defined ($user) and exists $self->{'_friend_group'}->{$group}) {
		my ($count) = 0;
		foreach my $friend (@{$self->friends()}) {
			if ($friend->{'user'} eq $user) {
				my $oldmask = $friend->{'groupmask'}
					? $friend->{'groupmask'}
					: 1;
				my $newmask = $oldmask ^ (1 << $group);
				if ($newmask > $oldmask) {
					carp ("$user is not in group $group");
					return undef;
				}
				$response = $self->editgroups({$group => {$user => $newmask}});
				last;
			}
			$count++;
		}
	}
	return $response;
}

sub editgroups {
	my ($self, $args) = @_;
	my $content = $self->_new_modeline('editfriendgroups');

	while (my ($k, $v) = each (%$args)) {
		for (keys (%$v)) {
			if ($_ eq "name" or $_ eq "sort" or $_ eq "public") {
				$content .= "&efg_set_" . $k . "_$_=" . $v->{$_};
			} else {
				$content .= "&editfriend_groupmask_" . $_ . "=" . $v->{$_};
			}
		}
	}
	my $response = $self->_send_mode($content);
	if ($response) {
		return {split("\n", $response->{_content})};
	} else {
		return undef;
	}
}

sub _cleargroups {
	my ($self, $numbers) = @_;

	my $friends = $self->friends;
	for my $num (@$numbers) {
		for my $friend (@$friends) {
			if (exists ($friend->{'groupmask'}) and
					($friend->{'groupmask'} & (2 ** $num))) {
				$self->remove_friend_from_group($friend->{'user'}, $num);
				$friend->{'groupmask'} ^= $num;
			}
		}
	}
	$self->friends($friends);
}

sub deletegroups {
	my ($self, $numbers) = @_;
	my $content = $self->_new_modeline('editfriendgroups');
	for my $num (@$numbers) {
		$content .= "&efg_delete_" . $num . "=1";
	}
	my $response = $self->_send_mode($content);
	if ($response->{'_content'}->{'success'} eq "OK") {
		$self->_cleargroups($numbers);
	}
	if ($response) {
		return {split("\n", $response->{'_content'})};
	} else {
		return undef;
	}
}

sub edit {
	my ($self, $hash) = @_;
	my $content = $self->_new_modeline('editfriends');
	my $num = 1;
	while (my ($k, $v) = each(%$hash)) {
		$content .= sprintf("&editfriend_add_%d_user=%s", $num, $k);
		for my $c (qw/fg bg/) {
			if (exists ($v->{$c})) {
				if ($v->{$c} =~ /^#[0-9A-F]{6}$/) {
					$content .= sprintf("&editfriend_add_%d_%s=%s", $num, $c, $v->{$c});
					$num++;
				} else {
					carp ("$c must be specified in #RRGGBB format in LiveJournal::Friend->edit().")
				}
			}
		}
	}
	my $response = $self->_send_mode($content);
	if ($response) {
		return {split("\n", $response->{_content})};
	} else {
		return undef;
	}
}

sub add {
	my ($self, $friend, $fg, $bg) = @_;
	my %hash;
	if (defined ($friend)) {
		$hash{$friend} = {};
	} else {
		carp ("LiveJournal::Friend->add() requires a username.");
		return undef;
	}
	if (defined ($fg)) {
		$hash{$friend}{'fg'} = $fg;
	}
	if (defined ($bg)) {
		$hash{$friend}{'bg'} = $bg;
	}
	my $response = $self->edit(\%hash);
	return $response;
}

sub remove {
	my ($self, $users) = @_;
	my $content = $self->_new_modeline('editfriends');
	for my $user (@$users) {
		$content .= "&editfriend_delete_" . $user . "=1";
	}
	my $response = $self->_send_mode($content);
	if ($response) {
		return {split("\n", $response->{_content})};
	} else {
		return undef;
	}
}

sub get {
	my ($self, $friendof, $groups) = @_;
	my $content = $self->_new_modeline('getfriends');
	if ($friendof) {
		$content .= "&includefriendof=1";
	}
	if ($groups) {
		$content .= "&includegroups=1";
	}

	my $response = $self->_send_mode($content);
	if ($response) {
		return {split("\n", $response->{'_content'})};
	} else {
		return undef;
	}
}

sub parse {
	my ($self, $args) = @_;
	my %hash;
	if ($args) {
		while (my ($k, $v) = each (%$args)) {
			if ($k =~ /(\w+)_(\d+)_(.*)/) {
				$hash{$1}[$2 - 1]{$3} = $v;
				$hash{$1}[$2 -1]{'number'} = $2 if ($3 eq "name");
			} elsif ($k =~ /frgrp_(\d+)_(\w+)/) {
				$self->friend_group($1, $2, $v);
			} elsif ($k eq "frgrp_maxnum") {
				$self->friend_group_max($v);
			}
		}
		if (exists ($hash{'friend'})) {
			$self->numfriends(scalar(@{$hash{'friend'}}));
		}
		$self->friends($hash{'friend'});
	} else {
		carp ("LiveJournal::Friend->parse() requires an arguement.");
	}
}

sub friendof {
	my ($self) = @_;
	my $content = $self->_new_modeline('friendof');
	my $response = $self->_send_mode($content);
	if ($response) {
		return {split("\n", $response->{'_content'})};
	} else {
		return undef;
	}
}

sub numfriends {
	my ($self) = shift;
	if (@_) {
		$self->{'_numfriends'} = shift;
	} else {
		return $self->{'_numfriends'};
	}
}

# XXX Should this be encapsulated?
sub lastupdate {
	my ($self) = shift;
	if (@_) {
		${$self->{'_lastupdate'}} = shift;
	} else {
		return ${$self->{'_lastupdate'}};
	}
}

sub friends {
	my ($self) = shift;
	if (@_) {
		my $arg = shift;
		@{$self->{'_friends'}} = @$arg;
	} else {
		return $self->{'_friends'};
	}
}

package LiveJournal::Journal;

use strict;
use Carp;

@LiveJournal::Journal::ISA = qw/LiveJournal/;

sub edit {
	my ($self, $args) = @_;
	my $content = $self->_new_modeline('editevent');

	for (qw/itemid event/) {
		unless (exists $args->{$_}) {
			carp ("Missing required value: $_ in LiveJournal::Journal->edit()");
			return undef;
		}
	}

	if (exists ($args->{'subject'}) and length($args->{'subject'}) > 255) {
		carp ("Subject too long; truncated to 255 chars in LiveJournal::Journal->edit().");
		substr($args->{subject}, 254) = '';
	}

	while (my ($k, $v) = each (%$args)) {
		$content .= "&" . $k . "=" . $v;
	}

  my (undef, $min, $hour, $day, $mon, $year) = localtime(time);

	$year += 1900;
  $mon = sprintf("%02d", $mon + 1);
  $day = sprintf("%02d", $day);
  $min = sprintf("%02d", $min);

	$content .= "&year=$year";
	$content .= "&mon=$mon";
	$content .= "&day=$day";
	$content .= "&hour=$hour";
	$content .= "&min=$min";

	my $response = $self->_send_mode($content);

	if ($response) {
		return {split("\n", $response->{_content})};
	} else {
		return undef;
	}
}

sub remove {
	my ($self, $itemids) = @_;

	unless (defined($itemids)) {
		carp ("LiveJournal::Journal->remove() requires item ids to remove.");
		return undef;
	}

	my $content = $self->_new_modeline('editevent');
	for my $id (@$itemids) {
		$content .= "&itemid=" . $id . "&event=";
	}
	my $response = $self->_send_mode($content);
	if ($response) {
		return {split("\n", $response->{_content})};
	} else {
		return undef;
	}
}

sub get {
	my ($self, $args) = @_;
	my $content = $self->_new_modeline('getevents');

	unless (exists ($args->{'selecttype'})) {
		carp ("Missing required key 'selecttype' in LiveJournal::Journal->get() hash");
		return undef;
	}

	if ($args->{'selecttype'} eq "syncitems" and
			not exists ($args->{'lastsync'})) {
		$args->{'lastsync'} = $self->lastsync();
	} elsif ($args->{'selecttype'} eq "day") {
		unless (exists ($args->{'year'}) and exists ($args->{'month'}) and
				exists ($args->{'day'})) {
			($args->{'day'}, $args->{'month'}, $args->{'year'}) =
				(localtime(time))[3,4,5];
			$args->{'year'} += 1900;
			$args->{'month'}++;
		}
	} elsif ($args->{'selecttype'} eq "lastn") {
		if (exists ($args->{'howmany'})) {
			if ($args->{'howmany'} > 50) {
				$args->{'howmany'} = 50;
			}
		} else {
			$args->{'howmany'} = 20;
		}
	} elsif ($args->{'selecttype'} eq "one" and not exists $args->{'itemid'}) {
		carp ("selecttype of 'one' requires key 'itemid' in LiveJournal::Journal->get()");
		return undef;
	}

	while (my ($k, $v) = each (%$args)) {
		$content .= "&" . $k . "=" . $v;
	}

	my $response = $self->_send_mode($content);

	if ($response) {
		return {split("\n", $response->{'_content'})};
	} else {
		return undef;
	}
}

sub post {
	my ($self, $args) = @_;
	my $content = $self->_new_modeline('postevent');

	unless (exists ($args->{'event'})) {
		carp ("Missing required key 'event' in LiveJournal::Journal->post() hash");
		return undef;
	}

	if (exists ($args->{'subject'}) and length($args->{subject}) > 255) {
		carp ("Subject too long; truncated to 255 chars in LiveJournal::Journal->post().");
		substr($args->{subject}, 254) = '';
	}

	while (my ($k, $v) = each (%$args)) {
		$content .= "&" . $k . "=" . $v;
	}

  my (undef, $min, $hour, $day, $mon, $year) = localtime(time);

	$year += 1900;
  $mon = sprintf("%02d", $mon + 1);
  $day = sprintf("%02d", $day);
  $min = sprintf("%02d", $min);

	$content .= "&year=$year";
	$content .= "&mon=$mon";
	$content .= "&day=$day";
	$content .= "&hour=$hour";
	$content .= "&min=$min";

	my $response = $self->_send_mode($content);
	if ($response) {
		return {split("\n", $response->{'_content'})};
	} else {
		return undef;
	}
}

sub getdaycounts {
	my ($self, $usejournal) = @_;
	my $content = $self->_new_modeline('getdaycounts');
	if (defined ($usejournal)) {
		$content .= "&usejournal=" . $usejournal;
	}
	my $response = $self->_send_mode($content);
	if ($response) {
		return {split("\n", $response->{'_content'})};
	} else {
		return undef;
	}
}

sub syncitems {
	my ($self) = @_;
	my $content = $self->_new_modeline('syncitems');
	$content .= "&lastsync=" . $self->lastsync();
	my $response = $self->_send_mode($content);
	if ($response) {
		my $hash = {split("\n", $response->{'_content'})};
		if ($hash->{'success'} eq "OK") {
			$self->lastsync($hash->{'lastsync'});
		}
		return $hash;
	} else {
		return undef;
	}
}

# XXX Should this be encapsulated?
sub lastsync {
	my ($self) = shift;
	if (@_) {
		${$self->{'_lastsync'}} = shift;
	} else {
		return ${$self->{'_lastsync'}};
	}
}

package LiveJournal::LiveJournalrc;

use strict;
use Carp;

sub _parse_rc {
	my ($files) = shift;

	unless (defined ($files)) {
		for my $fname ("$ENV{'HOME'}/.livejournalrc",
				"$ENV{'HOME'}/.livejournal.rc", "/etc/livejournalrc") {
			if (-r $fname) {
				push @$files, $fname;
				last;
			}
		}
		unless ($files) {
			carp ("No livejournalrc file found");
			return undef;
		}
	}

	my %rc;

	for my $file (@$files) {
		open (RC, $file) or do {
			carp ("Can't open config file '$file' for reading: $!");
			return undef;
		};


		while (defined (my $line = <RC>)) {
			$line =~ s/^\s+|\s+$//g;
			if ($line =~ /^([^:]+):\s*(.*)/) {
				$rc{$1} = $2;
			}
		}
	}

	return \%rc;
}

sub new {
	my (undef, $files) = @_;

	my $args = _parse_rc($files ? $files : undef);
	return undef unless defined ($args);

	my $self = LiveJournal->new($args);

	for (qw/datadir syncdir queuedir verbose/) {
		if (exists($args->{$_})) {
			$self->{"_$_"} = $args->{$_};
		}
	}

	bless ($self, "LiveJournal");
	return $self;
}

package LiveJournal;

use strict;
use LWP::UserAgent;
use Carp;
use vars qw($VERSION);

$VERSION = "1.1";

sub _send_mode {
	my ($self, $content) = @_;

	my $request = HTTP::Request->new('POST', $self->{'_URI'});
	$request->content_type('application/x-www-form-urlescaped');
	$request->content_length(length($content));
	$request->content($content);

	my $response = $self->{'_ua'}->request($request);

	if ($response->is_success()) {
		return $response;
	} else {
#		throw_error; # XXX ?
		return undef;
	}
}

sub _new_modeline {
	my ($self, $mode) = @_;
	if ($mode) {
		return (sprintf("mode=%s&user=%s&%spassword=%s", $mode,
			    $self->escape($self->user()),
			    (exists($self->{'_hpassword'}) ? 'h' : ''),
			    $self->escape($self->password())));
	} else {
		return undef;
	}
}

sub login {
	my ($self, $args) = @_;
	my $content = $self->_new_modeline('login');
	$content .= "&clientversion=" . $self->version();

	$content .= "&getmoods=" . $args->{'getmoods'} if (exists $args->{'getmoods'});
	$content .= "&getmenus=1" if (exists $args->{'getmenus'});
	$content .= "&getpickws=1" if (exists $args->{'getpickws'});

	my $response = $self->_send_mode($content);
	if (defined($response)) {
		return {split("\n", $response->{_content})};
	} else {
		return undef;
	}
}

sub escape {
	my ($self, $arg) = @_;
	$arg =~ s/([^a-zA-Z0-9\s])/uc(sprintf("%%%x", ord($1)))/ge;
	$arg =~ s/%20/+/g;
	return $arg;
}

sub parse_login {
	my ($self, $args) = @_;
	if ($args) {
		while (my ($k, $v) = each (%$args)) {
			if ($k =~ /access_\d+/) {
				$self->access($v);
#			} elsif ($k eq "access_count") {
#				$self->access_count($v);
			} elsif ($k =~ /frgrp_(\d+)_(\w+)/) {
				$self->friend_group($1, $2, $v);
			} elsif ($k eq "frgrp_maxnum") {
				$self->friend_group_max($v);
			} elsif ($k =~ /menu_(\d+)_(\d+)_(\w+)/) {
				$self->menu($1, $2, $3, $v);
#			} elsif ($k =~ /menu_(\d+)_count/) {
#				$self->menu_count($1, $v);
			} elsif ($k =~ /mood_(\d+)_(\w+)/) {
				$self->mood($1, $2, $v);
			} elsif ($k eq "mood_count") {
				$self->mood_count($v);
			} elsif ($k eq "name") {
				$self->name($v);
			} elsif ($k =~ /pickw_\d+/) {
				$self->pic_keyword($v);
#			} elsif ($k eq "pickw_count") {
#				$self->pic_count($v);
			}
		}
	} else {
		carp ("LiveJournal::->parse_login() requires an arguement.");
	}
}

{
	my ($args);
	my ($version, $lastupdate, $lastsync, $friend_group_max, $mood_count,
			$numfriends, $name, $command, $address, @friends, @access,
			%friend_group, @menu, @mood) = ("", "", "", 0, 0, 0, "", "", "");

	sub new {
		my ($proto) = shift;
		my $class = ref($proto) || $proto;
		my $self = {};

		if (@_) {
			$args = shift;
		} else {
			return undef unless $args;
		}

		if (exists($args->{'user'})) {
			$self->{'_user'} = $args->{'user'};
		} else {
			return undef;
		}

		if (exists($args->{'hpassword'})) {
			$self->{'_hpassword'} = $args->{'hpassword'};
		} elsif (exists($args->{'password'})) {
			$self->{'_password'} = $args->{'password'};
		} else {
			return undef;
		}

		if (exists ($args->{'url'})) {
			$self->{'_URI'} = URI->new($args->{'url'});
		} else {
			$self->{'_URI'} = URI->new("http://www.livejournal.com/cgi-bin/log.cgi");
		}

		$self->{'_ua'} = LWP::UserAgent->new();
		if (exists ($args->{'proxy'})) {
			$self->{'_ua'}->proxy('http', $args->{'proxy'});
		}

		$self->{'_command'} = \$command;
		${$self->{'_command'}} = $args->{'command'} if exists $args->{'command'};

		$self->{'_address'} = \$address;
		${$self->{'_address'}} = $args->{'address'} if exists $args->{'address'};

		$self->{'_version'} = \"Perl-archlj/$VERSION";

		$self->{'_lastupdate'} = \$lastupdate;
		$self->{'_lastsync'} = \$lastsync;
		$self->{'_numfriends'} = \$numfriends;
		$self->{'_friends'} = \@friends;
		$self->{'_access'} = \@access;
		$self->{'_friend_group'} = \%friend_group;
		$self->{'_friend_group_max'} = \$friend_group_max;
		$self->{'_menu'} = \@menu;
		$self->{'_mood'} = \@mood;
		$self->{'_mood_count'} = \$mood_count;
		$self->{'_name'} = \$name;

		bless ($self, $class);
		return $self;
	}
}

sub user {
	my ($self) = shift;
	return $self->{'_user'};
}

sub password {
	my ($self) = shift;
	return (exists ($self->{'_password'})
			? $self->{'_password'}
			: $self->{'_hpassword'});
}

sub version {
	my ($self) = shift;
	if (@_) {
		${$self->{'_version'}} = shift;
		return 0;
	} else {
		return ${$self->{'_version'}};
	}
}

sub access {
	my ($self) = shift;
	if (@_) {
		push @{$self->{'_access'}}, @_;
	} else {
		return $self->{'_access'};
	}
}

sub friend_group {
	my ($self) = shift;
	if (@_) {
		my ($num, $type, $val) = @_;
		$self->{'_friend_group'}{$num}{$type} = $val;
	} else {
		return $self->{'_friend_group'};
	}
}

sub friend_group_max {
	my ($self) = shift;
	if (@_) {
		${$self->{'_friend_group_max'}} = shift;
	} else {
		return ${$self->{'_friend_group_max'}};
	}
}

sub menu {
	my ($self) = shift;
	if (@_) {
		my ($menunum, $entrynum, $type, $val) = @_;
		$self->{'_menu'}[$menunum][$entrynum - 1]{$type} = $val;
	} else {
		return $self->{'_menu'};
	}
}

sub mood {
	my ($self) = shift;
	if (@_) {
		my ($num, $type, $val) = @_;
		$self->{'_mood'}[$num - 1]{$type} = $val;
	} else {
		return $self->{'_mood'};
	}
}

sub mood_count {
	my ($self) = shift;
	if (@_) {
		$self->{'_mood_count'} = shift;
	} else {
		return $self->{'_mood_count'};
	}
}

sub name {
	my ($self) = shift;
	if (@_) {
		${$self->{'_name'}} = shift;
	} else {
		return ${$self->{'_name'}};
	}
}

sub pic_keyword {
	my ($self) = shift;
	if (@_) {
		push @{$self->{'_pic_keyword'}}, shift;
	} else {
		return $self->{'_pic_keyword'};
	}
}

sub command {
	my ($self) = shift;
	if (@_) {
		${$self->{'_command'}} = shift;
	} else {
		return ${$self->{'_command'}};
	}
}

sub address {
	my ($self) = shift;
	if (@_) {
		${$self->{'_address'}} = shift;
	} else {
		return ${$self->{'_address'}};
	}
}

1;

=head1 NAME

LiveJournal - A Perl implementation of the LiveJournal protocol

=head1 SYNOPSIS

 use LiveJournal;

 my %info = (
	user => 'foo',
	password => 'bar',
 );

 my $lj = LiveJournal->new(\%info);

 my $response = $lj->login();

 print "Logged in successfully\n" if ($response->{success} eq "OK");

 ...

 my $friend = LiveJournal::Friend->new();

 my $response = $friend->check();

 ...

 my $journal = LiveJournal::Journal->new();

 my $response = $journal->syncitems();

=head1 DESCRIPTION

This module is implements the LiveJournal protocol.  See
http://www.livejournal.com/developer/protocol.bml for details.  Data is
requested from the server through I<mode lines>.  Many methods return a
hash reference containing key/value pairs returned by the server.
Descriptions of possible responses can be found at
http://www.livejournal.com/developer/modelist.bml

=head1 CONSTRUCTOR

=over 4

=item new (INFO)

This is the constructor for a new LiveJournal object.  C<INFO> is a hash
containing at least I<username> and I<password> (plaintext) or I<hpassword>
(MD5 hash) key/value pairs.  You may also include a I<URL>, for which the
default is http://www.livejournal.com/cgi-bin/log.cgi.  To use a proxy, add
a I<proxy> key and value.

=item LiveJournal::livejournal->new([ FILES ])

If you want to use a file in the livejournalrc format to store your data,
you can use this method instead.  C<FILES> is an array reference to the
file(s) you want to load.  If you don't specify any, it will use the first
one found of ~/.livejournalrc, ~/.livejournal.rc, or /etc/livejournalrc.
This will return an object in the LiveJournal class.

=back

=head1 BASE CLASS METHODS

=over 4

=item login ([ INFO ])

Log in to the LiveJournal server.  Returns a hash reference.  The server
returns whether the password is good or not, the user's name, an optional
message to be displayed to the user, and the list of the user's friend
groups.  C<INFO> is an optional hash reference containing the optional keys
B<getmoods>, B<getmenus>, and B<getpickws>.

B<getmoods> should exist and be the number of the highest mood ID you have
cached/stored on the user's computer. For example, if you logged in last
time with and got mood IDs 1, 2, 4, and 5, then send "5" as the value of
"getmoods". The server will return every new mood that has an internal
MoodID greater than 5. If you've never downloaded moods before, send "0".

B<getmenus> should exist if you want to get a list/tree of web
jump menus to show in your client.

B<getpickws> should exist if you want to receive that list of picture
keywords.

=item user ()

Returns the username

=item password ()

Returns the password or hpassword, whichever is set.

=item version ([VERSION])

Returns the version string.  You may alter the version string by passing a
C<VERSION>.

=item access ([ INFO ])

Sets/returns the journals that the user has the ability to post to.  This
method is called automatically by C<parse_login()>.  It returns a list
reference containing each journal.

=item friend_group ([ INFO ])

Sets/returns the friend group information.  This method is called
automatically by C<parse_login()>.  It returns a hash of hashes containing
B<name> and B<sortorder> key/value pairs.  We use a hash instead of an
array here because the group numbers start from 1 and it seemed more
appropriate than having an undef 0 element or requiring adding 1 all the
time.

=item friend_group_max ([ MAX ])

Sets/returns the maximum friend_group number.  This method is called
automatically by C<parse_login()>.

=item menu ([ INFO ])

Sets/returns the menu text and URL information.  This method is called
automatically by C<parse_login()>.  You can use the list of lists of hashes
it returns as data for menus.

=item mood ([ INFO ])

Sets/returns the mood information.  This method is called automatically by
C<parse_login()>.  Returns a list of hashes containing the keys B<id> and
B<name> for each mood.

=item mood_count ([ COUNT ])

Sets/returns the number of moods.  This method is called automatically by
C<parse_login()>.

=item name ([ NAME ])

Sets/returns the name of the the logged in user.  This method is called
automatically by C<parse_login()>.

=item pic_keyword ([ KEYWORDS ])

Sets/returns the picture keywords.  This method is called automatically by
C<parse_login()>.  Returns a reference to a list of the keywords.

=item escape (STRING)

Use this method to escape strings.  C<STRING> is any string.  All
non-alphanumeric characters and non-whitespace are converted to their %hex
values.  Spaces are converted to B<+>s.

=back

=head1 FRIEND METHODS

=over 4

=item check ()

Poll the server to see if the friends list has been updated. This request
is extremely quick, and is the preferred way for users to see when their
friends list is updated.  Returns a hash reference.

=item get ([ [ FRIENDOF ] [, GROUPS ] ])

Takes two optional arguements.  If C<FRIENDOF> is set to 1, you will also
get back the info from the "friendof" mode.  If C<GROUPS> is set to 1, you
will get the info from the "getfriendgroups" mode.  This method returns a
hash reference which should be passed to B<parse()> to be more
useful.  B<YOU SHOULD ALWAYS USE THIS METHOD BEFORE VIEWING AND AFTER
MODIFYING YOUR FRIENDS LIST TO AVOID INCONSISTENCIES.>

=item parse (FRIENDS)

Takes one arguement: the hash reference returned from B<get()>.
Returns a hash of lists of hashes containing the info (user, name, fg,
bg, etc) for each friend such as:

'friend' =E<gt>
    [
       {
        'fg'        =E<gt> '#000000',
        'bg'        =E<gt> '#FFFFFF',
        'groupmask' =E<gt> '3',
        'user'      =E<gt> 'SomeUser',
        'name'      =E<gt> 'Some X. Name'
       }
    ]

You should call B<parse()> anytime you call B<get()> to keep
your friend count up to date.

=item edit (FRIENDS)

This method is used to add and edit friends to your friends list.  It takes
a hash of hash references structure which has the B<username> as the first
level of keys.  The second level contains optional B<fg> and B<bg> colors
in #RRGGBB format.

'newfriend' =E<gt>
   {
    'fg' =E<gt> '#000000',
    'bg' =E<gt> '#FFFFFF',
   }

B<newfriend> is the name of the new user.  B<number> should be the
sum of C<numfriends() + n> where n is incremented for each
friend you are adding.

=item add (FRIEND, [ FG [, BG ] ])

Use this method to add a user from your friends list.  C<FRIEND> is a
username.  C<FG> and C<BG> are foreground and background values in #RRGGBB
format.

=item remove (USERS)

Use this method to remove users from your friends list.  Pass it an array
reference containing usernames.  Returns a hash reference.

=item friendof ()

This method returns a hash reference of the users that list you as a
friend.  This hash reference can be passed to B<parse()>.

=item lastupdate ([ LAST ])

Returns or sets the last time B<check> was used.  B<check()>
sets this value so you don't have to.

=item numfriends ([ NUMBER ])

This method sets and returns the number of friends you have.  It is
automatically called from B<parse()> so you shouldn't have to worry
about setting it manually.

=item friends ()

Sets and returns your friends list.  This method is called by
C<parse()> automatically to propagate the hash.

=item getgroups ()

This method returns a hash reference containing information about your
friend groups

=item editgroups (INFO)

Use this method to create or edit a friend group.  You can modify the name,
sort order, and public attributes of the group by passing a hashref
containing the keys called B<name>, B<sort>, or B<public> and respective
new values.  You can also add a friend to a group or groups by passing
their username as a key and the new groupmask as a value.

=item deletegroups (NUMBERS)

This method deletes a friend group.  Pass it an array reference containing
the numbers of the groups to delete.

=item friends_by_group () 

Returns a hash of list references containing users and the groups they are
members of.

=item add_friend_to_group (USER, GROUP)

Use this method to add a friend to a user group.  C<USER> is the username
of the person and C<GROUP> is the group number.

=item remove_friend_from_group (USER, GROUP)

Use this method to remove a friend from a user group.  C<USER> is the
username of the person and C<GROUP> is the group number.

=head1 JOURNAL METHODS

=item get (INFO)

Use this method to download parts of a user's journal.  C<INFO> is a hash
reference containing at least a key called B<selecttype> and a value of
either B<syncitems>, B<day>, B<lastn>, or B<one>.

B<syncitems> will use the C<lastcync()> method by default, otherwise pass
it a date in the I<yyyy-mm-dd hh::mm::ss> format.

If you use B<day>, you may provide B<year>, B<month>, and B<day> keys to
specify which day.  Default is today.

The B<lastn> value requires a B<howmany> key which says how many of the most
recent items to download.  Maximum is 50.  Default is 20.

If you want a particular entry, you should use the B<one> value and a
complimentary B<itemid> key containing the id of the item you want to grab.

For further detail, see
http://www.livejournal.com/developer/modeinfo.bml?getevents

=item post (INFO)

This method is used to post a journal entry.  C<INFO> is a hash reference
containing at least an B<event> key with a value of the post content.  The
date keys are created for you.

For further detail, see
http://www.livejournal.com/developer/modeinfo.bml?postevent

=item edit (INFO)

Used to edit user's past journal entry.  C<INFO> is a a hash reference
containing at least the I<itemid> and I<event> being submitted.  Other
optional values are documented at
http://www.livejournal.com/developer/modeinfo.bml?editevent

=item remove (ITEMID)

Used to delete a past journal entry.  C<ITEMID> is a scalar containing the
unique item id to delete.

=item syncitems ()

Returns a hash reference containing items (journal entries, to-do items,
comments) that have been created or updated on LiveJournal since you
last downloaded them.

=item lastsync ([ LAST ])

Returns or sets the last time B<syncitems()> was used.  B<syncitems()> sets
this value so you don't have to.

=item getdaycounts ()

This mode retrieves the number of journal entries per day. Useful for
populating calendar widgets in GUI clients.

=back

=head1 AUTHOR

Frank Sheiness <archon@forbidden.dough.net>
http://feeding.frenzy.com/~rainking/

=head1 CREDITS

=over

=item *

Brad 'bradfitz' Fitz <bradfitz@livejournal.com> for unconfusing me


=item *

Joe 'pinman' Wreschnig <piman@sacredchao.net> for his idea providing
ventures into Perl-LiveJournal land

=back

=head1 URL

=over

=item *

http://forbidden.dough.net/~archon/lj/

=head1 SEE ALSO

=item *

perl(1).

=item *

http://www.livejournal.com/developer/

=back

=cut
