1: #! /usr/bin/perl -w
2: #
3: # The script to post mail messages to LiveJournal
4: # (see http://mail2lj.nichego.net/ for original).
5: #
6: # Changes by LG (all are labelled by '# Changed by LG' string):
7: # - Removed all references to Mail2LJ::Config and $cfg (just as author's
8: # comment below says).
9: # - Changed $host definition.
10: # - Changed location of mimemtmp subdirectory from $HOME to /tmp
11: # - Changed location and name of log file to $HOME/mail/mail2lj.log
12: # - In bounces and responces replaced charset from Windows-1251 to koi8-r
13: # - Added comment-parsing settings (keyword Comments: can be "no" or "off"
14: # to forbid comments, or "noemail" to not email comments). If not set,
15: # falls back to Journal's Default, obviously.
16: # - Removed "[mail2lj]" label in the subject.
17: #
18: # ! - Added command line parsing. Now all the keywords can be specified
19: # on the command line (see '-h' for help). Collected options are passed
20: # on to the posting subroutine and *override* corresponding body keywords
21: # values (e.g., now you can specify '--usejournal' when posting via
22: # 'hpost-(user)-(MD5Hash)' alias). As an added bonus, now it's possible
23: # to post COMPLETELY without body keywords (via either 'post',
24: # 'post-(user)-(password) or 'hpost-(user)-(MD5Hash)' aliases), so you
25: # can use the script as a general purpose mail-to-LJ-anywhere gateway.
26: # E.g. it'll work great in procmail.
27: #
28: # ! - Changed recipient of bounce messages in send_bounce() function to allow
29: # optional designation of custom error recipient (as opposed to strictly
30: # original From: address). This is convenient when you want to notify
31: # script maintainer instead of the poster (exactly what I need).
32: #
33: #
34: # NB: to generate MD5 hash of your password, use the following command:
35: # perl -MDigest::MD5 -e 'print Digest::MD5::md5_hex("yourpassword")."\n"'
36: #
37: #
38: # Adopted by Lev Gorenstein <lev@ledorub.poxod.com> from the original
39: # script by jason@nichego.net (http://livejournal.com/users/jsn/) which
40: # is available at http://mail2lj.nichego.net/
41: #
42: # Original script seems to be distributed as freeware, so I stick to that
43: # decision. No warranty whatsoever, of course - use at your own risk ;-).
44: #
45: # Changes by Boris Veytsman - added --cut option
46: #
47: # ------------------------------------------------------------------------
48:
49: use strict ;
50:
51: use Getopt::Long;
52: use LWP::UserAgent ;
53: use HTTP::Request ;
54: use URI::Escape ;
55: use MIME::Parser ;
56: use MIME::Words qw/decode_mimewords encode_mimeword/ ;
57: use Unicode::MapUTF8 qw/to_utf8 from_utf8/ ;
58: use HTML::TokeParser ;
59:
60: # Changed by LG - commented out configs.
61: # use Mail2LJ::Config ; # you can just remove every line mentioning
62: # # Mail2LJ::Config or $cfg
63: #
64: # my $cfg = $Mail2LJ::Config::conf ;
65:
66: # Changed by LG - added shorname and version.
67: (my $shortname = $0) =~ s/^.*\///; # script name without path
68: my $Version = "0.9"; # Version number
69: my $LGmod = "-LG"; # Version modifier by LG
70:
71:
72: my $post_uri = "http://www.livejournal.com/cgi-bin/log.cgi" ;
73: my $ljcomment_action = 'http://www.livejournal.com/talkpost_do.bml';
74: # my $host = $ENV{MAIL2LJ_DOMAIN} || "mail2lj.nichego.net" ; # Changed by LG
75: # my $host = $ENV{MAIL2LJ_DOMAIN} || `hostname -f` ; # Changed by LG
76: my $host = $ENV{MAIL2LJ_DOMAIN} || "ledorub.poxod.com" ; # Changed by LG
77: # my $home = $ENV{HOME} || "/home/mail2lj" ; # Changed by LG
78: my $home = $ENV{HOME} || "/tmp/mail2lj" ;
79:
80: # Changed by LG - added because sometimes procmail doesn't set $USER.
81: my $SysUser = $ENV{USER} || $ENV{LOGNAME} || getpwuid($>) || $> ;
82:
83: # Changed by LG. Specifies the default incoming and outgoing charset for
84: # all e-mails (i.e, the posts CONTENT and the script replies).
85: # For incoming mails, the MIME header is analyzed and actual MIME charset
86: # overrides the default, of course.
87: # my $MailCharset = "cp1251";
88: my $MailCharset = "koi8-r";
89:
90: # Changed by LG. Specifies the charset in which non-English characters
91: # FROM THE COMMAND LINE are entered. I.e. if I give a command line option
92: # '--subject ôÅÓÔ', the script needs to know the encoding to properly convert
93: # it to UTF8. I'm too lazy to analyze current locale, so I'll make it the
94: # user's responsibility. Override via '--charset' option.
95: # my $SystemCharset = "cp1251";
96: # my $SystemCharset = "utf8";
97: my $SystemCharset = "koi8-r";
98:
99:
100: # Translation table for smstrip_data() function. Only used whith aliases
101: # ljreply-... and ljreplys-...
102: my %tr = (
103: 'á' => 'A', 'â' => 'B', '÷' => 'V', 'ç' => 'G', 'ä' => 'D', 'å' => 'E', '³' =>
104: 'E', 'ö' => 'Zh', 'ú' => 'Z', 'é' => 'I', 'ê' => 'J', 'ë' => 'K', 'ì' => 'L',
105: 'í' => 'M', 'î' => 'N', 'ï' => 'O', 'ð' => 'P', 'ò' => 'R', 'ó' => 'S', 'ô' =>
106: 'T', 'õ' => 'U', 'æ' => 'F', 'è' => 'H', 'ã' => 'C', 'þ' => 'Ch', 'ý' => 'Sch',
107: 'û' => 'Sh', 'ø' => '\'', 'ù' => 'Y', 'ÿ' => '\'', 'ü' => 'E', 'à' => 'Yu',
108: 'ñ' => 'Ya', 'Á' => 'a', 'Â' => 'b', '×' => 'v', 'Ç' => 'g', 'Ä' => 'd', 'Å' =>
109: 'e', '£' => 'e', 'Ö' => 'zh', 'Ú' => 'z', 'É' => 'i', 'Ê' => 'i', 'Ë' => 'k',
110: 'Ì' => 'l', 'Í' => 'm', 'Î' => 'n', 'Ï' => 'o', 'Ð' => 'p', 'Ò' => 'r', 'Ó' =>
111: 's', 'Ô' => 't', 'Õ' => 'u', 'Æ' => 'f', 'È' => 'h', 'Ã' => 'c', 'Þ' => 'ch',
112: 'Û' => 'sh', 'Ý' => 'sch', 'Ø' => '\'', 'Ù' => 'y', 'ß' => '\'', 'Ü' => 'e',
113: 'À' => 'yu', 'Ñ' => 'ya'
114: );
115:
116: # ------------------------------------------------------------------------ #
117: # End configuration settings.
118: # ------------------------------------------------------------------------ #
119:
120:
121: # ------------------------------------------------------------------------ #
122: # Changed by LG - added parsing of command line.
123: # Changed by BV - added options cut
124: # ------------------------------------------------------------------------ #
125: my %Opt = (); # Main options go here
126: my $opt_h ; # Help flag
127: my $opt_bounces ; # Alternative error recipient flag
128: my $opt_addfrom ; # Add the From field to the post
129: my $opt_addfromh ; # Add the htmlized From to the post
130: my $opt_keepspaces ; # HTML-encode multiple spaces in e-mail
131: my @opt_taglist ; # command-line taglist first goes here
132: my $opt_ljcut ; # Add lj-cut after line number N
133: my $ljcut_delta = 5 ; # No lj-cut if less lines left after it
134: my $opt_ljcut_text ; # A text for lj-cut.
135: my $Parse = GetOptions( \%Opt,
136: 'user|u=s',
137: 'password|passwd|p=s',
138: 'hpassword|hpasswd|hp=s',
139: 'date|d=s',
140: 'security|sec=s',
141: 'prop_opt_preformatted|formatted|f!',
142: 'prop_opt_backdated|backdated|back-dated|backdate|back-date|back!',
143: 'subject|subj|s=s',
144: 'taglist|tags|tag|t=s' => \@opt_taglist, # Will tweak
145: 'notaglist|notags|notag|not|no-taglist|no-tags|no-tag|no-t' => sub {undef @opt_taglist},
146: 'usejournal|use-journal|use|journal|j=s',
147: 'prop_current_mood|current_mood|mood=s',
148: 'prop_current_music|current_music|music=s',
149: 'prop_picture_keyword|picture_keyword|picture|pic|userpic=s',
150: 'comments|comment|c=s', # Will tweak below
151: 'charset|enc=s' => \$SystemCharset,
152: 'bounces|bounce|b=s' => \$opt_bounces,
153: 'addfrom|add-from|from!' => \$opt_addfrom,
154: 'addfromh|add-fromh|fromh!' => \$opt_addfromh,
155: 'ljcut|lj-cut|cut|l=i'=>\$opt_ljcut,
156: 'ljcut-text|lj-cut-text|cut-text|ljcuttext|cuttext=s'=>\$opt_ljcut_text,
157: 'keep-spaces|keep-space|keepspaces|keepspace|spaces|space!' => \$opt_keepspaces,
158: 'help|h' => \$opt_h,
159: );
160:
161: # Handle bad options
162: if ( ! $Parse ) {
163: print_usage('short');
164: die "Run with '-h' for more help.\n\n";
165: }
166:
167: # Print help if requested.
168: print_usage('long'), exit 0 if ($opt_h);
169:
170:
171: # Check if '--date' was specified and convert hash value to proper format
172: # for LJ request.
173: if ( exists $Opt{'date'} ) {
174: # Note: "DD.MM.YYYY HH:MM". Single-digit day, month and hour are allowed.
175: # Double-digit "YY" is also allowed and considered "2000 + YY"
176: if ( $Opt{'date'} =~ /(\d\d?)\.(\d\d?)\.(\d{2,4})\s+(\d\d?):(\d\d)/ ) {
177: $Opt{'day'} = $1 ;
178: $Opt{'mon'} = $2 ;
179: $Opt{'year'} = $3 ;
180: $Opt{'hour'} = $4 ;
181: $Opt{'min'} = $5 ;
182: $Opt{'year'} += 2000 if $Opt{'year'} < 100 ;
183: } else {
184: print STDERR "can't parse date '$Opt{'date'}', using current.\n" ;
185: }
186: delete $Opt{'date'} ; # And remove the old element.
187: }
188:
189:
190:
191: # Comments option is 'comments yes/no/nomail', but LJ wants
192: # 'prop_opt_*no*comments' property. Keep command line human-readable and
193: # switch to proper value in the hash.
194: if ( exists $Opt{'comments'} ) {
195: if ( $Opt{'comments'} =~ /^s*((on)|(yes)|(default))\s*$/i ) {
196: $Opt{'prop_opt_nocomments'} = "" ;
197: } elsif ( $Opt{'comments'} =~ /^\s*(noe?mails?)\s*$/i ) {
198: $Opt{'prop_opt_nocomments'} = "" ;
199: $Opt{'prop_opt_noemail'} = 1 ;
200: } elsif ( $Opt{'comments'} =~ /^\s*((off)|(no))\s*$/i ) {
201: $Opt{'prop_opt_nocomments'} = 1
202: } else {
203: $Opt{'prop_opt_nocomments'} = $Opt{'comments'} ;
204: }
205: delete $Opt{'comments'} ; # And remove the old element.
206: }
207:
208:
209: # Convert taglist array into a single string and store it
210: # with other parameters.
211: $Opt{'prop_taglist'} = join( ", ", @opt_taglist ) if ( @opt_taglist ) ;
212:
213: # Convert $opt_ljcut_text to UTF8.
214: if ( defined $opt_ljcut_text ) {
215: $opt_ljcut_text =
216: to_utf8({ -string => $opt_ljcut_text, -charset => $SystemCharset }) ;
217: }
218:
219: # Convert all %Opt command line options to unicode.
220: # Function href2utf8() uses a reference to input hash, so %Opt is
221: # being modified "in-place".
222: href2utf8( \%Opt, $SystemCharset) ;
223:
224:
225: # Changed by LG - set a restrictive umask (we're talking mail files here!)
226: umask 077 ;
227:
228:
229: # Changed by LG - moved from above.
230: my $alias = shift @ARGV || "none" ;
231: my $mp = new MIME::Parser() or die "new MIME::Parser(): $!\n" ;
232:
233:
234: # Changed by LG - changed directory to be user and process-specific.
235: # $mp->output_dir("$home/mimetmp") ;
236: $mp->output_dir("/tmp/mimetmp-" . $SysUser . "-$$") ;
237: mkdir $mp->output_dir if not -d $mp->output_dir ; # Create it if missing
238:
239: # Get the whole mail.
240: # Changed by LG - added removal of output directory.
241: my $me = $mp->parse(\*STDIN) ;
242: END { $me and $me->purge() ;
243: rmdir $mp->output_dir if -d $mp->output_dir
244: or print STDERR "Error removing $mp->output_dir: $!\n" ;
245: } ;
246:
247:
248: # Changed by LG - different log file name.
249: # open(STDERR, ">>$home/generic.log") or die "open(`log'): $!\n" ;
250: my $logdir = "$home/mail" ;
251: mkdir $logdir if not -d $logdir ; # Create it if missing
252: open(STDERR, ">>$logdir/mail2lj.log") or die "open(`log'): $!\n" ;
253:
254: my $users = {} ;
255: # $users = $cfg->{users} ;
256:
257: # Get mail header.
258: my $mh = $me->head() ;
259: $me->dump_skeleton(\*STDERR) ;
260:
261: # Changed by LG - added chomping of "To:" field.
262: my $to = $me->get('To') || "" ;
263: chomp $to ;
264: print STDERR "Alias: $alias\n", "To: $to\n",
265: "Charset: ", $mh->mime_attr("content-type.charset") || "NONE", "\n" ;
266:
267: my $xmailer = $mh->get('X-Mailer') || "unknown" ;
268: if ($xmailer =~ /EPOC/ || $xmailer =~ /Eudora.+PalmOS/) {
269: # too bad. they do violate standards there.
270: $mh->mime_attr("content-type.charset" => "windows-1251") ;
271: print STDERR "Charset changed to 'windows-1251' (hopefully)\n" ;
272: }
273:
274:
275: # And here we do posting.
276: if ($alias =~ /MAILER-DAEMON/i) {
277: exit 0 ;
278: } elsif ($alias =~ /^post$/) {
279: # my $req = post_me2req($me, "windows-1251") ; # Changed by LG
280: my $req = post_me2req($me, "$MailCharset", { %Opt }) ; # Changed by LG
281: my $ljres = submit_request($req) ;
282:
283: if ($ljres->{'success'} eq "OK") {
284: print STDERR "journal updated successfully\n" ;
285: } else {
286: print STDERR "error updating journal: $ljres->{errmsg}\n" ;
287: send_bounce($ljres->{errmsg}, $me, $mh->mime_attr("content-type.charset")) ;
288: }
289: } elsif ($alias =~ /^post-(\w+)-(\w+)$/) {
290: my $l = $1 ;
291: my $p = $2 ;
292: # my $req = post_me2req($me, "windows-1251", { # Changed by LG
293: # user => $l,
294: # password => $p
295: my $req = post_me2req($me, "$MailCharset", { # Changed by LG
296: user => $l,
297: password => $p,
298: %Opt # Changed by LG
299: }) ;
300: my $ljres = submit_request($req) ;
301:
302: if ($ljres->{'success'} eq "OK") {
303: print STDERR "journal updated successfully\n" ;
304: } else {
305: print STDERR "error updating journal: $ljres->{errmsg}\n" ;
306: send_bounce($ljres->{errmsg}, $me, $mh->mime_attr("content-type.charset")) ;
307: }
308: } elsif ($alias =~ /^hpost-(\w+)-(\w+)$/) {
309: my $l = $1 ;
310: my $hp = $2 ;
311: # my $req = post_me2req($me, "windows-1251", { # Changed by LG
312: # user => $l,
313: # hpassword => $hp
314: my $req = post_me2req($me, "$MailCharset", { # Changed by LG
315: user => $l,
316: hpassword => $hp,
317: %Opt # Changed by LG
318: }) ;
319: my $ljres = submit_request($req) ;
320:
321: if ($ljres->{'success'} eq "OK") {
322: print STDERR "journal updated successfully\n" ;
323: } else {
324: print STDERR "error updating journal: $ljres->{errmsg}\n" ;
325: send_bounce($ljres->{errmsg}, $me, $mh->mime_attr("content-type.charset")) ;
326: }
327: } elsif ($alias =~ /^ljreply-(\S+)$/ || $alias =~ /^ljreplys-(\S+)$/) {
328: my $email = $1 ;
329: $email =~ s/\.\./\@/ ;
330:
331: if ($mh->get('From') !~ m/lj_dontreply\@livejournal.com/ &&
332: $mh->get('From') !~ m/lj_notify\@livejournal.com/) {
333: # someone just picked our email from livejournal.com site
334: print STDERR "no livejournal signature found, bouncing to $email\n";
335: $mh->replace('To', $email) ;
336: $me->send("sendmail") ;
337: exit 0 ;
338: }
339:
340: die "ljreply doesn't look like a 2-part message.\n"
341: unless $me->parts() == 2 ;
342: my $formdata = ljcomment_form2string
343: $me->parts(1)->bodyhandle->as_string() ;
344: # Changed by LG - changed to a variable.
345: # my $charset =
346: # ($me->parts(0)->head->mime_attr('content-type.charset') ||
347: # "windows-1251") ;
348: my $charset =
349: ($me->parts(0)->head->mime_attr('content-type.charset') ||
350: "$MailCharset") ;
351: my $data = $me->parts(0)->bodyhandle->as_string() ;
352:
353: my $nicefrom = "Mail2LJ-translated comment" ;
354: if ($mh->get("From") =~ /\(([^\)]+)\)/) {
355: $nicefrom = $1 ;
356: }
357: print STDERR "nicefrom is '$nicefrom'\n" ;
358:
359: if ($alias =~ /^ljreplys/) {
360: print STDERR "stripping content...\n" ;
361: $data = to_utf8({ -string => $data, -charset => $charset})
362: if $charset !~ /^utf-?8$/i ;
363: # Changed by LG - changed to a variable.
364: # $data = from_utf8({ -string => $data, -charset => "cp1251"}) ;
365: # $charset = "windows-1251" ;
366: $data = from_utf8({ -string => $data, -charset => "$MailCharset"}) ;
367: $charset = "$MailCharset" ;
368: $data = smstrip_data $data ;
369: }
370:
371: my $msg = build MIME::Entity(
372: 'From' => "ljfrom-$formdata\@$host",
373: # 'Sender' => "ljfrom-$formdata\@$host",
374: 'To' => $email,
375: 'Subject' => normalize_header($mh->get('Subject'), $charset),
376: 'Content-Type' => "text/plain; charset=$charset" ,
377: 'Data' => $data
378: );
379: $msg->send("sendmail") ;
380: $msg->purge() ;
381: } elsif ($alias =~ /^ljfrom-(\S+)$/) {
382: my $formdata = $1 ;
383: my $hr = ljcomment_string2form($formdata) ;
384: my $req = new HTTP::Request('POST' => $ljcomment_action)
385: or die "new HTTP::Request(): $!\n" ;
386:
387: $hr->{usertype} = 'user' ;
388: # Changed by LG.
389: # $hr->{encoding} = $mh->mime_attr('content-type.charset') ||
390: # "cp1251" ;
391: $hr->{encoding} = $mh->mime_attr('content-type.charset') ||
392: "$MailCharset" ;
393: $hr->{subject} = decode_mimewords($mh->get('Subject'));
394: $hr->{body} = $me->bodyhandle->as_string() ;
395:
396: $req->content_type('application/x-www-form-urlencoded');
397: $req->content(href2string($hr)) ;
398:
399: my $ljres = submit_request($req, "comment") ;
400:
401: if ($ljres->{'success'} eq "OK") {
402: print STDERR "journal updated successfully\n" ;
403: } else {
404: print STDERR "error updating journal: $ljres->{errmsg}\n" ;
405: send_bounce($ljres->{errmsg}, $me, $mh->mime_attr("content-type.charset")) ;
406: }
407: }
408: print STDERR "-------------------------------------------------------------\n" ;
409:
410:
411: # ------------------------------------------------------------------------- #
412: # All done.
413: # ------------------------------------------------------------------------- #
414: exit 0 ;
415:
416:
417:
418: # ------------------------------------------------------------------------- #
419: # Subroutines from now down.
420: # ------------------------------------------------------------------------- #
421: sub href2utf8 {
422: my ($hr, $e) = @_ ;
423: my $i ;
424:
425: foreach $i (keys %$hr) {
426: $hr->{$i} = to_utf8({ -string => $hr->{$i}, -charset => $e}) ;
427: }
428: return $hr ;
429: }
430:
431: sub href2string {
432: my $hr = shift ;
433: my $i ;
434: my $s = "" ;
435:
436: foreach $i (keys %$hr) {
437: next if $i eq "event" ;
438: $s .= "&" if $s ;
439: $s .= $i . "=" . uri_escape($hr->{$i}, "^A-Za-z0-9") ;
440: }
441:
442: if ($hr->{event}) {
443: $s .= "&" if $s ;
444: $s .= "event=" . uri_escape($hr->{event}, "^A-Za-z0-9") ;
445: }
446: return $s ;
447: }
448:
449: sub post_body2href {
450: my $fh = shift ;
451: my ($l, $auth) ;
452: my $req_data = {
453: webversion => 'full',
454: ver => 1,
455: security => 'public',
456: prop_opt_preformatted => 0,
457: mode => 'postevent'
458: } ;
459:
460: while ($l = $fh->getline()) {
461: if (exists $req_data->{event}) {
462: $req_data->{event} .= $l ;
463: next ;
464: }
465:
466: next if $l =~ /^$/ ;
467:
468: if ($l =~ /^(\w[\w_]*[\w])\s*[=:]\s*(\S.*)$/) {
469: my ($var, $val) = (lc($1), $2) ;
470:
471: if ($var eq "date") {
472: # Changed by LG.
473: # Note: "DD.MM.YYYY HH:MM". Single-digit day, month and
474: # hour are allowed. Double-digit "YY" is also allowed
475: # and considered "2000 + YY".
476: if ($val =~ /(\d\d?)\.(\d\d?)\.(\d{2,4})\s+(\d\d?):(\d\d)/) {
477: $req_data->{day} = $1 ;
478: $req_data->{mon} = $2 ;
479: $req_data->{year} = $3 ;
480: $req_data->{hour} = $4 ;
481: $req_data->{min} = $5 ;
482: $req_data->{year} += 2000 if $req_data->{year} < 100 ;
483: } else {
484: print STDERR "can't parse date '$val', will use current\n" ;
485: }
486: } elsif ($var eq "mood" || $var eq "current_mood") {
487: $req_data->{prop_current_mood} = $val ;
488: } elsif ($var eq "music" || $var eq "current_music") {
489: $req_data->{prop_current_music} = $val ;
490: } elsif ($var eq "picture" || $var eq "picture_keyword") {
491: $req_data->{prop_picture_keyword} = $val ;
492: } elsif ($var eq "formatted" || $var eq "autoformat") {
493: $val = 1 if $val =~ /^\s*((on)|(yes))\s*$/i ;
494: $val = 0 if $val =~ /^\s*((off)|(no))\s*$/i ;
495: # Changed by LG - "autoformat" is opposite to "formatted".
496: # Add 0 to make sure it's the number.
497: $val = 0 + (not $val) if ($var eq "autoformat") ;
498: $req_data->{prop_opt_preformatted} = $val ;
499: } elsif ($var eq "auth") {
500: $auth = $val ;
501:
502: # Changed by LG - added 'backdated' option. Remember,
503: # Livejournal currently prohibits backdated entries in the
504: # communities (as opposed to individual journals).
505: } elsif ($var =~ /^back-?dated?$/ || $var eq "opt_backdated") {
506: $val = 1 if $val =~ /^\s*((on)|(yes))\s*$/i ;
507: $val = 0 if $val =~ /^\s*((off)|(no))\s*$/i ;
508: $req_data->{prop_opt_backdated} = $val ;
509:
510: # Changed by LG - added comment-parsing settings.
511: # Comments: default/on/yes | off/no | nomail
512: # Assembled based on data from form values in the browser
513: # and from info on
514: # http://www.livejournal.com/doc/server/ljp.csp.flat.postevent.html
515: # http://www.livejournal.com/doc/server/ljp.csp.proplist.html
516: } elsif ($var eq "comments" || $var eq "comment"
517: || $var eq "comment_settings"
518: || $var eq "comments_settings" ) {
519: if ( $val =~ /^\s*((on)|(yes)|(default))\s*$/i ) {
520: # Journal default
521: $val = "" ;
522: $req_data->{comment_settings} = $val ;
523: $req_data->{prop_opt_nocomments} = $val ;
524: } elsif ( $val =~ /^\s*(noe?mails?)\s*$/i ) {
525: # No emails
526: $val = "1" ;
527: $req_data->{prop_opt_nocomments} = (not $val) + 0;
528: $req_data->{prop_opt_noemail} = $val ;
529: } elsif ( $val =~ /^\s*((off)|(no))\s*$/i ) {
530: # No comments
531: $val = "1" ;
532: $req_data->{prop_opt_nocomments} = $val ;
533: } else {
534: # Anything else.
535: $req_data->{comment_settings} = $val ;
536: }
537:
538: # Changed by LG - added 'tags' option.
539: } elsif ($var =~ /^tags?$/ || $var eq "taglist") {
540: $req_data->{prop_taglist} = $val;
541:
542: # Changed by LG - added 'notags' option. Empty the preceding
543: # taglist if set to true, otherwise do nothing
544: } elsif ($var =~ /^no-?tags?$/ || $var eq "no-?taglist") {
545: $req_data->{prop_taglist} = "" if $val =~ /^\s*((on)|(yes))\s*$/i ;
546:
547: # Anything else - just assign.
548: } else {
549: $req_data->{$var} = $val ;
550: }
551: } else {
552: $req_data->{event} = $l ;
553: }
554: }
555:
556: if (!exists $req_data->{year}) {
557: my @lt = localtime() ;
558: $req_data->{day} = $lt[3] ;
559: $req_data->{mon} = $lt[4] + 1 ;
560: $req_data->{year} = 1900 + $lt[5] ;
561: $req_data->{hour} = $lt[2] ;
562: $req_data->{min} = $lt[1] ;
563: }
564:
565: if ($auth) {
566: $req_data->{password} = $users->{$req_data->{user}}->{password}
567: if exists $users->{$req_data->{user}} &&
568: $users->{$req_data->{user}}->{auth} eq $auth ;
569: }
570:
571: return $req_data ;
572: }
573:
574: sub hdr2utf8 {
575: my ($s, $e) = @_ ;
576: my $r = "" ;
577: my $i ;
578:
579: foreach $i (decode_mimewords $s) {
580: $r .= to_utf8({
581: -string => $i->[0],
582: -charset => ($i->[1] || $e)
583: }) ;
584: }
585:
586: return $r ;
587: }
588:
589:
590: # Changed by LG - added this subroutine for a shortcut call to to_utf8().
591: # All it does is conversion of a string to utf8.
592: sub str2utf8 {
593: my ($s, $e) = @_;
594: my $r = "" ;
595:
596: $r .= to_utf8({ -string => $s, -charset => $e }) ;
597: return $r ;
598: }
599:
600: sub post_me2req {
601: my ($me, $e, $hints) = @_ ;
602: my $mebh = $me->bodyhandle() or die "post_message(): no body?\n" ;
603: my $mehh = $me->head() ;
604: my $charset = $mehh->mime_attr("content-type.charset") || $e ;
605: my $subject = hdr2utf8($me->get('Subject') || "", $charset) ;
606: chomp $subject ; # Changed by LG
607: # Changed by LG.
608: my $from = hdr2utf8($me->get('From') || "", $charset) ;
609: chomp $from ;
610:
611: my $hr = href2utf8(post_body2href($mebh->open("r")), $charset) ;
612: my $req = new HTTP::Request('POST', $post_uri) or
613: die "new HTTP::Request(): $!\n" ;
614:
615: if ($hints) {
616: my $i ;
617: foreach $i (keys %$hints) {
618: # Changed by LG - make hints override (not just complement)
619: # existing values.
620: # $hr->{$i} ||= $hints->{$i} ;
621: $hr->{$i} = $hints->{$i} ;
622: }
623: }
624:
625: $hr->{subject} ||= $subject ;
626: # Changed by LG - removed prefixing.
627: # $hr->{subject} = "[mail2lj] " . $hr->{subject} ;
628:
629: # Changed by LG - added options to add the plain or HTML-ized 'From'
630: # field to the posted message.
631: #
632: # NOTE: $from is already in UTF8, but the "From:" and HTML tags are
633: # not. Strictly speaking, everything that goes to $hr->{event}
634: # MUST ALSO BE IN UTF8. A cheating shortcut is possible:
635: # since all lower ASCII characters are guaranteed to have
636: # the same values in UTF8 as in plain ISO-8859-1, you could
637: # possibly stick ASCII strings to $from without risk. But in
638: # order to add something non-ASCII, you absolutely MUST convert
639: # it to UTF8 first! To avoid the risk of forgetting this, the
640: # following substitutions are done in a _proper_ (albeit
641: # somewhat awkward) way.
642: if ( $opt_addfrom || $opt_addfromh ) {
643:
644: # Assemble the added From string in UTF8.
645: my $added_from ;
646: if ( $opt_addfrom ) {
647: $added_from = str2utf8("From: ", "ISO-8859-1")
648: . $from . str2utf8("\n\n", "ISO-8859-1") ;
649: } elsif ( $opt_addfromh ) {
650: $added_from = str2utf8("<nobr><i><b>From:</b> ", "ISO-8859-1" )
651: . $from
652: . str2utf8("</i></nobr>\n\n", "ISO-8859-1") ;
653: }
654:
655: # Obfuscate the address.
656: my $olddog = str2utf8("\@", "ISO-8859-1") ; # @ in utf8
657: my $newdog = str2utf8("[_\@_]", "ISO-8859-1") ; # [_@_] in utf8
658: $added_from =~ s/$olddog/$newdog/g ; # Obfuscate
659: $hr->{event} = $added_from . $hr->{event} ; # And append
660: }
661:
662: # Changed by LG - added an option to preserve (html-ize) multiple
663: # spaces and tabs (convert '\t' to eight ' ' and convert
664: # multiple continuous spaces into sequence of ' ').
665: # Lines with tabs are additionally wrapped in <nobr>...</nobr> tags.
666: #
667: # NOTE: These tags should be in UTF8. But since HTML tags themselves
668: # are *certainly* in lower ASCII, we can safely stick them on
669: # top of the existing UTF8 post. But if you dare to add
670: # anything more than ASCII-markup, you'd better str2utf8() it
671: # first! See note in the $opt_addfrom/$opt_addfromh processing above.
672: if ( $opt_keepspaces ) {
673: $hr->{event} =~ s/^(.*\t.*)$/<nobr>$1<\/nobr>/gm ;
674: $hr->{event} =~ s/\t/\ \ \ \ \ \ \ \ /g ;
675: $hr->{event} =~ s/ / \ /g ;
676: }
677:
678: #
679: # Change by BV - added the option to put lj-cut after '--cut XX' lines
680: #
681: # Tweaked by LG - only adding lj-cut if more than $ljcut_delta lines
682: # is left in the posting. Also added $opt_ljcut_text.
683: #
684: if ($opt_ljcut>0) {
685: my $nlines = scalar( my @junk=split( /\n/, $hr->{event}, -1) ) - 1;
686: my $start=0;
687: for (my $i=0; $i<$opt_ljcut; $i++) {
688: $start=index($hr->{event},"\n",$start)+1;
689: if ($start == 0) {
690: last;
691: }
692: }
693: # And insert the lj-cut if not too close to the end of the post.
694: if ($start>0 ) {
695: if ( $nlines >= $opt_ljcut+$ljcut_delta ) {
696: my $ljcut = ( $opt_ljcut_text =~ /^\s*$/ ) ?
697: '<lj-cut>' :
698: '<lj-cut text="' . $opt_ljcut_text . '">' ;
699: substr($hr->{event}, $start,0) = $ljcut ;
700: } else {
701: print STDERR "'--cut $opt_ljcut' requested, which is " .
702: "within $ljcut_delta of the total $nlines " .
703: "lines. Skipping lj-cut.\n" ;
704: }
705: }
706: }
707:
708: $req->content_type('application/x-www-form-urlencoded');
709: $req->content(href2string $hr) ;
710:
711: print STDERR "working on request from $hr->{user}\n",
712: "From: $from\n", # Changed by LG
713: "Date: ", scalar localtime, "\n" ;
714:
715: return $req ;
716: }
717:
718: sub submit_request {
719: my ($req, $proto) = @_ ;
720: my $ljres = {} ;
721: my $ua = new LWP::UserAgent or
722: die "new LWP::UserAgent: $!\n" ;
723: # Changed by LG - modified user-agent
724: # $ua->agent("Mail2LJ/0.9");
725: $ua->agent("Mail2LJ/${Version}${LGmod}");
726: $ua->timeout(100);
727: my $res = $ua->request($req);
728:
729: if ($proto && $proto eq "comment") {
730: if ($res->is_success) {
731: $ljres->{'success'} = "OK";
732: } else {
733: $ljres->{'success'} = "FAIL";
734: $ljres->{'errmsg'} = "Client error: Error contacting server.";
735: }
736:
737: return $ljres ;
738: }
739:
740: if ($res->is_success) {
741: %$ljres = split(/\n/, $res->content);
742: } else {
743: $ljres->{'success'} = "FAIL";
744: $ljres->{'errmsg'} = "Client error: Error contacting server.";
745: }
746: return $ljres ;
747: }
748:
749: sub ljcomment_form2string {
750: my $s = shift ;
751: my $h = {} ;
752: my $p = new HTML::TokeParser(\$s) or
753: die "new HTML::TokeParser(): $!\n" ;
754: my $token = $p->get_tag("form");
755: die "get_inputs(): Wrong form.\n"
756: if ($token->[1]{action} ne $ljcomment_action) ;
757:
758: while ($token = $p->get_tag("input") ) {
759: $h->{$token->[1]{name}} =
760: $token->[1]{value} || '' if ($token->[1]{name});
761: }
762:
763: die "get_inputs(): Incomplete form data\n"
764: unless $h->{userpost} && $h->{journal} && $h->{parenttalkid} &&
765: $h->{itemid} && $h->{ecphash} ;
766:
767: $h->{ecphash} =~ s/^ecph-// ;
768:
769: return "$h->{userpost}-$h->{journal}-$h->{parenttalkid}-$h->{itemid}-$h->{ecphash}" ;
770: }
771:
772: sub ljcomment_string2form {
773: my $s = shift ;
774: my $hr = {} ;
775: my $i ;
776: my @l = split /\-/, $s ;
777:
778: foreach $i (qw/userpost journal parenttalkid itemid ecphash/) {
779: $hr->{$i} = shift @l ;
780: }
781:
782: die "badly formed formdata '$s'\n" unless $hr->{ecphash} ;
783: $hr->{ecphash} = "ecph-" . $hr->{ecphash} ;
784:
785: return $hr ;
786: }
787:
788: sub normalize_header {
789: my ($s, $e) = @_ ;
790: my $d = decode_mimewords($s) ;
791: chomp $d ;
792:
793: return encode_mimeword($d, 'B', $e) ;
794: }
795:
796:
797: sub smstrip_data {
798: my $data = shift ;
799: my ($hdr, $ftr) ;
800: my ($who, $journal) ;
801:
802: $data =~ /^(.+)Their reply was:(.+)You can view the discussion(.+)$/si
803: or return $data ;
804: $hdr = $1 ;
805: $data = $2 ;
806: $ftr = $3 ;
807:
808: $hdr =~ /\((\w+)\) replied to .* ((post)|(comment))/ and $who = $1 ;
809:
810: $ftr =~ m,http://www\.livejournal\.com/talkpost.bml\?journal=(\w+),
811: and $journal = $1 ;
812:
813: if ($who) {
814: $data = "user [$who] in [$journal]:\n" . $data ;
815: }
816:
817: $data =~ s/^\s+Subject:\s*$//m ;
818: $data =~ s/^\s+Subject:\s(\S.*)\s*$/[$1]/m ;
819: $data =~ s/\s+/ /gs ;
820: $data =~ s/(.)/$tr{$1} || $1/ge ;
821:
822: return $data ;
823: }
824:
825: sub send_bounce {
826: my ($errmsg, $orig, $charset) = @_ ;
827:
828: # Changed by LG - use KOI-8 instead of Win-1251.
829: # $charset ||= "windows-1251" ;
830: $charset ||= "$MailCharset" ;
831:
832: my $bmsg = build MIME::Entity(
833: 'From' => "MAILER-DAEMON\@$host",
834: # Changed by LG - allow use of alternative addres for notifications.
835: # 'To' => $orig->get('From'),
836: 'To' => $opt_bounces || $orig->get('From'),
837: 'Subject' => (
838: "mail2lj failure (was: " . $orig->get('Subject') . ")"
839: ),
840: 'Content-Type' => "text/plain; charset=$charset" ,
841: 'Data' => <<EOF
842:
843: Dear Mail2Lj User,
844:
845: Mail2Lj gateway at $host was trying hard to submit your request,
846: but, unfortunately, to no avail: a silly, but fatal error has occured.
847: Mail2Lj(tm) proudly presents the extremely informative error message:
848:
849: '$errmsg'
850:
851: Thank you for understanding,
852: good luck next time,
853: take care,
854: sincerely, completely and, in general, very truly yours,
855: -Mail2Lj.
856: EOF
857: );
858: $bmsg->send("sendmail") ;
859: $bmsg->purge() ;
860: }
861:
862:
863: sub print_usage {
864: # ----------------------------------------------------------------------- #
865: # print_usage( $Long );
866: #
867: # Prints help message. If defined $Long, the message is more detailed
868: # as opposed to default brief description.
869: # ----------------------------------------------------------------------- #
870: my ( $long ) = @_; # Were we called with a parameter?
871:
872: my $spacer = ' ' x length($shortname); # bunch of spaces
873:
874: # ---------------------------------------------------------------------
875: # Short usage will always be printed when called.
876: # Indentation messed up because of the HERE-document.
877: # ---------------------------------------------------------------------
878: print <<___END_SHORT;
879: $shortname v. ${Version} by jason\@nichego.net (http://jsn.livejournal.com).
880: Tweaked to v. ${Version}${LGmod} by Lev Gorenstein \<lev\@ledorub.poxod.com\>, 2007.
881:
882: Usage:
883: $shortname ACTION [options] < InputFile
884: cat MailMessage | $shortname ACTION [options]
885:
886: A script to post incoming mail messages to Livejournal.com journals.
887: Reads STDIN and connects to Livejournal's HTTP posting interface.
888:
889: This is a modification of mail2lj.pl script by Jason
890: (http://jsn.livejournal.com) described at http://mail2lj.nichego.net/.
891: I added command line processing and couple more tweaks.
892:
893: Distributed freely under GNU Public License with absolutely no warranty.
894:
895: ___END_SHORT
896:
897:
898: # ---------------------------------------------------------------------
899: # When called in a long format, usage should be followed by some more info.
900: # Indentation messed up because of the HERE-document.
901: # ---------------------------------------------------------------------
902: if ( defined $long && $long !~ /^\s*short\s*$/i ) {
903: print <<______END_HELP;
904: ACTIONS:
905: post Original script used this to handle messages that had keywords
906: inside (see http://mail2lj.nichego.net/userguide.html) and
907: used 'post-...' and 'hpost-...' to post keywordless messages
908: directly. This version doesn't require keywords (i.e. 'post'
909: can handle keywordless messages and everything can be set via
910: command line), but if you DO use keywords, then use this action.
911:
912: post-(user)-(password)
913: A direct post of mail message (without looking for keywords in
914: the body) using whatever settings supplied on the command line.
915: With proper command line parameters, username and password can
916: be completely bogus (i.e. 'post-aa-bb -u RealUser -p RealPass').
917:
918: hpost-(user)-(MD5Hash_of_password)
919: A direct post of mail message (without looking for keywords in
920: the body) using whatever settings supplied on the command line,
921: Same as 'post-...', but uses a password hash instead of
922: clear-text password.
923: With proper command line parameters, username and hash can be
924: completely bogus (i.e. 'hpost-aa-bb -u RealUser --hp RealHash').
925:
926:
927: Options:
928: -u USER, --user USER
929: Use this LiveJournal user name to login.
930:
931: -p PASS, --password PASS
932: Use this LiveJournal password to login. Use of this option
933: is deprecated because of clear-text password.
934:
935: -hp MD5Hash, --hpassword MD5Hash
936: Use this MD5 hash of the password to login. To generate a hash,
937: do this:
938: perl -MDigest::MD5 \
939: -e 'print Digest::MD5::md5_hex("PASSWORD")."\\n"'
940:
941: -j JOURNAL, --usejournal JOURNAL
942: When posting to the community (or the journal that's different
943: from the one you've specified via '--user'), use this option
944: to specify that community's name. E.g. if the user
945: 'gusarskie_vesti' wants to post to community 'gusary', it can
946: be done with options like this:
947: post -u gusarskie_vesti -p PASS --usejournal gusary
948:
949: -s SUBJECT, --subject SUBJECT
950: Use this subject for the posting. If absent, defaults to
951: e-mail's Subject:.
952:
953: -t TAGLIST, --tags TAGLIST
954: Use tags from TAGLIST for posted message. Within a tag list,
955: tags should be separated by commas. If your tags contain
956: special characters or spaces, make sure to enclose TAGLIST in
957: single or double quotes to protect from the shell. Multiple
958: '-t' options are allowed and taglists will be combined.
959:
960: --notaglist, --notags
961: Unsets all previously defined tags. Thus, a call to
962: $shortname ... --tags X --tags Y ... --notags --tags Z
963: will yield a taglist consisting of just "Z". This option is
964: rarely needed and added only for the sake of completeness.
965:
966: -d DATE, --date DATE
967: Label posting with this date. Date should be in LiveJournal's
968: format: DD.MM.YYYY HH:mm. If absent, current date/time is used.
969:
970: --backdated
971: If set, tells LiveJournal to make this message back-dated
972: (i.e. to set 'Date out-of-order' flag to prevent this item
973: from showing in people's friends lists). Note that currently
974: Livejournal only allows back-dated entries in individual
975: journals (not in communities), so use with caution. The option
976: can be negated ('--nobackdated'). Default is '--nobackdated'.
977:
978: --security public|protected|private
979: Post security mode. Default is "public".
980:
981: -f, --formatted
982: If set, tells LiveJournal to assume our message to be already
983: formatted (i.e. '--formatted' turns OFF LJ's autoformat
984: feature). The option can be negated ('--noformatted').
985: Default is '--noformatted' (i.e. *use* LJ's autoformat).
986:
987: --mood MOOD Current Mood for Livejournal. TEXT ONLY (images not supported).
988: Defaults to nothing.
989:
990: --music MUSIC Current Music for Livejournal. Defaults to nothing.
991:
992: --picture KEYWORD, --userpic KEYWORD
993: Keyword for the Livejournal userpic to use. Default one is
994: used when not specified.
995:
996: -c on|yes|default|off|no|noemail, --comments on|yes|default|off|no|noemail
997: Controls permissions to leave comments for this post.
998: "on" ("yes", "default") will use the journal's default settings.
999: "off" or "no" prohibit comments. "noemail" allows comments,
1000: but tells Livejournal not to email them to you.
1001:
1002: --from, --addfrom
1003: Insert the From: field from the e-mail as the first line of
1004: the posted message. The field is added in plain text (without
1005: any HTML-formatting - see '--fromh' for that). For slight
1006: antispam protection, '\@' is replaced by '[_\@_]'. The option
1007: can be negated ('--nofrom'). Default is '--nofrom'.
1008:
1009: --fromh, --addfromh
1010: Same as '--from', but uses HTML-markup to highlight inserted
1011: field (<nobr><i><b>From:</b> Address</i></nobr>). This is
1012: nice for mailing list -> Livejournal crossposting. The option
1013: can be negated ('--nofromh'). Default is '--nofromh'.
1014:
1015: --spaces, --keepspaces
1016: Normally the script does not change original message text,
1017: and all of it is preserved in the body of resulting LJ post.
1018: Which means that all tabs and multiple consecutive spaces
1019: (while valid in e-mail and preserved in the post), will not
1020: be properly *shown* in the browser (browser will display them
1021: as single space). With '--spaces', however, all tabs will
1022: be converted to 8 '\ ' instances, and each pair of
1023: consecutive spaces will be converted to a ' \ ' sequence.
1024: Additionally, lines with tabs will be wrapped in <nobr> tag.
1025: This way the formatting of original e-mail will be much
1026: better preserved in the journal. The option can be negated
1027: ('--nospaces'). Default is '--nospaces'.
1028:
1029: --ljcut NUM, --cut NUM, -l NUM
1030: Inserts '<lj-cut>' after NUM lines of the post content.
1031: If the resulting lj-cut happens to be within $ljcut_delta lines from
1032: the end of the post, the cut will not be added.
1033:
1034: --ljcut-text TEXT, --cut-text TEXT, --cuttext TEXT
1035: Text to use as lj-cut text parameter (in <lj-cut text="TEXT">).
1036: If the text contains nothing but whitespace, it is ignored.
1037: Remember to quote spaces and special characters from the shell.
1038:
1039: --charset CHARSET
1040: This option tells the script that all COMMAND LINE options are
1041: given in this charset. Default is "$SystemCharset".
1042: Remember, THIS HAS NOTHING TO DO with the __posting's charset__
1043: (which is determined from email headers and then converted to
1044: utf8). It also has absolutely no effect on the in-the-body
1045: keywords (they are also governed by email's charset). This
1046: option is meaningful ONLY for the text that you supply VIA
1047: COMMAND LINE (e.g. '-s Subject' or '--cuttext TEXT').
1048:
1049: -b xxx\@yyy, --bounces xxx\@yyy
1050: Normally, if errors occur during posting (e.g. wrong password),
1051: the script sends an error notification to the _original poster_
1052: (i.e., the address in the original From: field). This makes
1053: perfect sense for multi-user installations. But occasionally
1054: there is a need to send all errors to a single _maintainer_
1055: (e.g., if you use the script as a mailing list --> LiveJournal
1056: gateway). This option allows exactly that. Default is unset
1057: (i.e. errors go to original poster).
1058:
1059: -h, --help: This help.
1060:
1061:
1062: If you decide to use keywords in the body of the message (as opposed to
1063: command line options), they should look like this:
1064:
1065: From: .... \\
1066: To: .... + # Regular e-mail headers
1067: Subject: ... /
1068: # Normal blank line after headers
1069: User: gusarskie_vesti
1070: Password: password # (or Hpassword: MD5Hash)
1071: Date: 22.01.2007 5:04
1072: Security: private
1073: Subject: Rzhevskij zhiv!
1074: Tags: Junk, Viva Rzhevskij!
1075: Notags: yes # Clears all preceding tags
1076: Formatted: on # Or equivalent "Autoformat: off"
1077: Usejournal: gusary
1078: Mood: okay
1079: Music: silence
1080: Backdated: yes
1081: Comments: no
1082: # Blank line
1083: Oh well. some text # Text of your message.
1084:
1085: And the text would be posted.
1086:
1087: Almost all keyword fields (as well as their command line counterparts)
1088: are optional and have reasonable defaults. The only mandatory parameter
1089: is the user name (well, doh!). See more on keywords in the original
1090: script's user guide: http://mail2lj.nichego.net/userguide.html
1091:
1092: ______END_HELP
1093: print "\n";
1094: } # End of "if $long" test
1095:
1096: # ---------------------------------------------------------------------
1097: # All done
1098: # ---------------------------------------------------------------------
1099:
1100: return;
1101: }
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>