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