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