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