Current location

narf Source control manager Git

summaryrefslogtreecommitdiff
blob: 448dbb3bb1000a3af23854fdc8d35f472b70fa58 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
#!/usr/bin/perl -w
#-*-perl-*-
#  $UpstreamSource: /opt/cvs/root/scripts/blog/WordPressImport.pl,v $
#  $UpstreamRevision: 1.7 $
#  $UpstreamDate: 2009/02/03 20:45:13 $
#  $UpstreamAuthor: will $
#  $Source: /opt/cvs/root/scripts/blog/WordPressImport.pl,v $
#  $Revision: 1.7 $
#  $Date: 2009/02/03 20:45:13 $
#  $Author: will $

=pod

=head1 SYNOPSIS

B<WordPressImport.pl> <options> [command]

=head1 DESCRIPTION

B<WordPressImport.pl> is a migration utility to convert a SimplePHPBlog 
directory to a WordPress MySQL database.

SimplePHPBlog stores the entire blog in a single directory. This utilty
will extract posts, comments, links, blocks and categories and write them 
into the WordPress MySQL database.

It can be used on a fresh WordPress installation or an existing one, though
the former is recommended for simplicity.

Running this import utility multiple times will not duplicate entries in your database, all entries are first check to see if they already exist.

B<Ratings Plugin>

You need to have the 'postratings' plugin installed in order for the ratings to be 
imported - this can be overriden using the -noratings switch.

To install this plugin, goto this page http://wordpress.org/extend/plugins/wp-postratings
and follow the installation instructions.

Don't forget to activate the plugin after you've installed it!

B<Operation>

This utility will import the folling into the database:

  SimplePHPBlog     Wordpress
  -------------     ---------
  Posts             Posts
  Comments          Comments
  Categories        Categories 
  Links             Blogroll
  Static            Pages 
  Blocks            Pages

B<Simple Instructions>

Starting from a fresh installation for WordPress, here are the steps:
 1.  Create wordpress database, or run B<WordPressImport.pl -create> command (See below)
 2.  Extract postratings plugin to wp-content/plugins directory (optional)
 3.  Edit wp-content/themes/<your theme>/index.php and after:
        <?php while (have_posts()) : the_post(); ?>
     insert:
        <?php if(function_exists('the_ratings')) { the_ratings(); } ?>
 4.  Open browser to your WordPress site
 5.  Enter Blog Title and email fields
 6.  Click "Install Wordpress"
 7.  Login with supplied password
 8.  Click "My Profile" in top right hand corner
 9.  Change admin email password
 10. Click on "Plugins"
 11. Activate "WP-PostRatings" and "WP-PostRatings Widget" plugins (if installed) 
 12. Run B<WordPressImport.pl -import> command (See Below)
 13. Check any errors or problems and continue using WordPress

=cut 

use strict;
use DBI();
use Date::Format;
use Getopt::Long;

my $version="0.8sh";

my %OPTS = ( host => 'localhost', 
			 user => 'root', 
			 database => 'wordpress', 
			 wp_username => 'wordpress',
			 verbose => 0);

my @OPTIONS= (
	"user=s",
	"host=s",
	"database=s",
	"password:s",
	"wp_password=s",
	"wp_username=s",
	"blogid=s",
	"import=s",
	"noratings",
	"create",
	"drop",
	"help",
	"verbose+",
);

sub usage {
	print "
Usage: $0 [options] command
options:
    -host         - database hostname (def: $OPTS{host})
    -user         - database username (def: $OPTS{user})
    -password     - database password (prompted if empty)
    -database     - database name (def: $OPTS{database})
    -wp_username  - wordpress username (def: $OPTS{wp_username})
    -wp_password  - wordpress database password (see wp-config.php)
    -blogid       - id of the blog in MultiSite configuration (>1)
    -noratings    - do not import ratings
    -help         - this help
    -verbose      - verbose output - specify multiple times for increased verbosity
commands:
    -import [dir] - import blog from directory dir
    -drop         - drop $OPTS{database} database
    -create       - create $OPTS{database} and set permissions
    
    current version is $version
";
	exit 0;
}

=pod

=head1 OPTIONS

 -host         - database hostname (default: localhost)
 -user         - database username (default: root)
 -password     - database password. If no password is supplied then you'll
                 be prompted for on from the console.
 -database     - database name (default: 'wordpress')
 -wp_password  - wordpress database password (must match password in wp-config.php)
 -wp_username  - wordpress username (def: 'wordpress')
 -blogid       - id of the blog in MultiSite configuration (>1)
 -noratings    - do not import ratings (in case postratings plugin not installed)
 -help         - this helpful help
 -verbose      - verbose output - specify multiple times for increased verbosity


=head1 COMMANDS

 -import [dir] - import blog from directory dir
 -drop         - drop wordpress database (caution: 'drop' is database speak for 'trash')
 -create       - create wordpress database and set permissions

=head1 EXAMPLES

B<Conditions>

SimplePHPBlog blog in a directory called 'sphpblog'. 

username/password for the MySQL database is "root/trickypassword". The assumption is that
you have correctly installed and configured MySQL. If your database is across a network then
ensure that you have granted correct permissions to this username in order that they in turn
can grant correct permissions to the 'wordpress' user.

The password in wp-config.php file is "bananas". This is reqired for WordPress to
read and write to/from the database

The database is on the current machine, localhost

1. First, we start from scratch and completely delete the wordpress database:

B<./WordPressImport.pl -host localhost -user root -password trickypassword -drop>

2. Now we recreate it. We need the -wp_password option for the database to authenticate WordPress

B<./WordPressImport.pl -host localhost -user root -password trickypassword -wp_password bananas -create>

3. Import the SimplePHPBlog blog directory "sphpblog/"

B<./WordPressImport.pl -host localhost -user root -password trickypassword -wp_password bananas -import sphpblog/>

If you do not supply a value to the -password option, then you'll be prompted for it on the command line. If the -password option is not supplied at all, then it assumes that you have no password in your database (and you should hang your head in shame).

You'll see a summary of the data imported. To increase verbosity, supply the -v (-verbose) option. Repeated switches will increase the verbosity (-v -v -v is very verbose).

=head1 BUGS

The category hierarchy is not preservered at present - not convinced it was particulalry useful anyway in SimplePHPBlog

This utility was tested with SimplePHPBlog version 0.4.5 and 0.5.11

=head1 REVISION HISTORY

 Revision 0.8 2014-04-16

 0.1 Initial revision
 0.2 fixed ratings
 0.3 Now handles posts with multiple categories. Parses html code from blocks.
 0.4 Debug bug...
 0.5 Support pre-0.4.6.1 versions
 0.6 fixed import bug on wp_term_relationships table
 0.7 ratings needs to be written as floating point
 0.8sh update for WP 3.8.x, add support for MultiSite blogs, compressed data and absent links

=head1 AUTHOR

This implementation written by Will Hall 
I<dev@innerhippy.com>

Support 3.8.x, MultiSite and compression by Olivier Mehani 
I<shtrom-wordpress@ssji.net>

=head1 COPYRIGHT and LICENSE

Copyright 2008 Innerhippy Software Corporation. All rights reserved.
Copyright 2014 Olivier Mehani. All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice,this
list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY WILLIAM HALL`AS IS' AND ANY EXPRESS
OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
EVENT SHALL WILLIAM HALL BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,DATA,
OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

The views and conclusions contained in the software and documentation are
those of the author and should not be interpreted as representing official
policies, either expressed or implied, anywhere.

=head1 SEE ALSO

=head1 NEXT TOPIC

=cut

my $DBH;
my $blogid="";

usage() if !GetOptions(\%OPTS,@OPTIONS) or $OPTS{help};

if ($OPTS{drop}) {
	print "This will delete the whole database - sure? [y/N] ";
	chomp (my $ans = <>);
	$ans eq 'y' || exit;
	dbConnect($OPTS{database});
	dropDatabase();
}

if ($OPTS{create}) {
	dbConnect('mysql');
	createDatabase();
}

if ($OPTS{blogid}) {
	$blogid="$OPTS{blogid}_";
}

if ($OPTS{import}) {
	dbConnect($OPTS{database});

	my $wp = WordPressImport->new($OPTS{import});
	my $categories = $wp->get_categories();
	addCategories ($categories);
	addLinks ($wp->get_links);
	addPosts ($wp->get_posts, $categories);
	addStatic ($wp->get_static);
	addBlocks ($wp->get_blocks);
	updateCatCount();
}

loggit ("ok");
$DBH && $DBH->disconnect;

sub loggit {
	my ($str, $level) = @_;
	$level||=0;
	return if $level > $OPTS{verbose};
	print STDOUT "$str\n";
}

sub error_exit {
	loggit "Error: @_\n";
	$DBH && $DBH->disconnect;
	exit 1;
}

sub slug {
	my $str = shift;
	$str =~ s/[ ]/-/g;
	return lc $str;
}
sub updateCatCount {
	# Multiple rows returned so can't use runSelSQL
	my $sth = $DBH->prepare("SELECT term_taxonomy_id 
							 FROM wp_${blogid}term_relationships group by term_taxonomy_id") or die $DBH->errstr;
	$sth->execute(@_);
	my @cats;
	while (	my $row = $sth->fetchrow_arrayref) {
		push @cats, $row->[0];
	}
	$sth->finish;
	foreach my $taxonomy_id (@cats) {
		runSQL ("UPDATE wp_${blogid}term_taxonomy tt 
				 SET tt.count = ( select count(*) 
				 			      FROM wp_${blogid}term_relationships tr 
								  WHERE tr.term_taxonomy_id = tt.term_taxonomy_id ) 
				 WHERE tt.term_taxonomy_id = ?", $taxonomy_id);
	}
}

sub addEntry {
	my ($cats, $subject, $date, $content, $type) = @_;

	if ( (runSelSQL ("SELECT * FROM wp_${blogid}posts 
					  WHERE post_title=?
					  AND post_type=?", $subject, $type))[0]) {
		loggit ("Post exists: '$subject'", 1);
		return;
	}
	runSQL ("INSERT INTO wp_${blogid}posts (
					post_author, post_date, post_date_gmt, post_content, post_title, 
					post_excerpt, post_password, post_name, to_ping, 
					pinged, post_modified, post_modified_gmt, post_content_filtered, 
					guid, post_mime_type, post_type)
			 VALUES (1,?,?,?,?,'','',?,'','',?,?,'',0,'',?)", 
					$date, $date, $content, $subject,
					slug($subject), $date, $date, $type);

	my $siteurl = (runSelSQL ("SELECT option_value FROM wp_${blogid}options WHERE option_name='siteurl'"))[0] 
				  || error_exit "Cannot get siteurl from options table";
	my $insert_id = $DBH->last_insert_id(undef, undef, 'wp_${blogid}posts', 'ID');
	runSQL ("UPDATE wp_${blogid}posts SET guid=? WHERE post_title=?", "$siteurl/?p=$insert_id", $subject);

	foreach my $category (@$cats) {
		my $category_id=(runSelSQL (qq{SELECT term_taxonomy_id 
								   	FROM wp_${blogid}term_taxonomy,wp_${blogid}terms
					      		   	WHERE  wp_${blogid}term_taxonomy.term_id = wp_${blogid}terms.term_id 
				  		  		   	AND wp_${blogid}terms.name = ?}, $category))[0] 
					 	|| die "lost category '$category'";


		runSQL ("INSERT INTO wp_${blogid}term_relationships (object_id, term_taxonomy_id) 
			 	VALUES (?,?)", $insert_id, $category_id);
	}
	return $insert_id;
}

sub addStatic {
	my ($static) = @_;
	my ($added, $skipped)=(0,0);

	foreach my $s (@$static) {
		my $id = addEntry (['Uncategorized'], $s->{subject},$s->{date},$s->{content},'page');
		if ($id) {
			$added++;
			loggit ("Added pages '$s->{subject}'", 1);
		} else {
			$skipped++;
		}
	}
	loggit ("Added $added, skipped $skipped static as pages");
}

sub addBlocks {
	my ($blocks) = @_;
	my ($added, $skipped)=(0,0);

	foreach my $b (@$blocks) {
		my $id = addEntry (['Uncategorized'], $b->{subject},"0000-00-00 00:00:00" ,$b->{content},'page');
		if ($id) {
			$added++;
			loggit ("Added blocks '$b->{subject}'", 1);
		} else {
			$skipped++;
		}
	}
	loggit ("Added $added, skipped $skipped blocks as pages");
}

sub addPosts {
	my ($posts, $categories) = @_;
	unless ($OPTS{noratings}) {
		(runSelSQL("SELECT table_name 
					FROM information_schema.tables
					WHERE table_schema = '$OPTS{database}'
					AND table_name = 'wp_ratings'"))[0] 
					|| error_exit "postratings plugin not installed or activated";
	}

	my ($added, $skipped)=(0,0);
	foreach my $p (@$posts) {
		my @cat_names;
		foreach ($p->{categories}) {
			push @cat_names, $categories->{$_} || "Uncategorized"; # This should exist
		}
		# Make the entries in @cat_names unique
		my %categories = map { $_ => 1 } @cat_names;
		@cat_names = keys %categories;
		my $id = addEntry (\@cat_names, $p->{subject},$p->{date},$p->{content},'post');
		if ($id) {
			$added++;
			my $n = addComments ($p->get_comments, $id);
			loggit ("Added post '$p->{subject}' with $n comments", 1);
			addRating ($p->{points}, $p->{votes}, $id, $p->{subject});
		} else {
			$skipped++;
		}
	}
	loggit ("Added $added, skipped $skipped posts");
}

sub addRating {
	my ($points, $votes, $id, $subject) = @_;
	$OPTS{noratings} && return;
	my $max = (runSelSQL ("SELECT option_value FROM wp_${blogid}options WHERE option_name='postratings_max'"))[0];
	
	$points = sprintf ("%.0f", ($points||0)*$max/5);
	my $avg = sprintf ("%.2f", ($points||0)/($votes||1)); # average rating score for max rating = 5

	runSQL ("INSERT INTO wp_${blogid}postmeta (post_id, meta_key, meta_value) 
			 VALUES (?,'ratings_users',?), (?, 'ratings_score', ?), (?, 'ratings_average', ?)", 
			 $id, $votes, $id, $points, $id, $avg);
}

sub addComments {
	my ($comments, $id) = @_;
	my $i=0;
	foreach my $c (@$comments) {
		$i++;
		runSQL ("INSERT INTO wp_${blogid}comments (comment_post_ID, comment_author, 
							comment_author_email, comment_author_url, comment_author_IP, 
							comment_date, comment_date_gmt, comment_content, comment_agent, 
							comment_type) 
				VALUES (?, ?, ?, ?, '', ?, ?, ?, '', '')",
							$id, $c->{name}, $c->{email}, $c->{url}, $c->{date}, $c->{date}, $c->{content});
	}
	# Update comment count
	runSQL ("UPDATE wp_${blogid}posts set comment_count=? where ID=?", $i, $id);
	return $i;
}
sub addCategories {
	my $cat = shift;
	my ($added, $skipped) = (0,0);

	# Make sure there's one called 'Uncategorized'
	unless ( (runSelSQL ("SELECT term_id FROM wp_${blogid}terms
					  	  WHERE name='Uncategorized'"))[0]) {
		# find next category number free
		my $max;
		$max = $_ foreach (sort keys %$cat);
		$cat->{$max +1} = 'Uncategorized';
	}

	
	foreach (keys %$cat) {
		if ((runSelSQL("SELECT term_id,name from wp_${blogid}terms WHERE name=?", $cat->{$_}))[0]) {
			loggit ("category exists: $cat->{$_}", 1);
			$skipped++;
			next;
		}
		my $slug = slug ($cat->{$_});
		runSQL("INSERT INTO wp_${blogid}terms (name,slug,term_group) VALUES (?, ?, 0)", $cat->{$_}, $slug);
		my $insert_id = $DBH->last_insert_id(undef, undef, 'wp_${blogid}terms', 'term_id');
		runSQL("INSERT INTO wp_${blogid}term_taxonomy (term_id, taxonomy, description, parent, count)
				VALUES (?, 'category','',0,1)", $insert_id);
		$added++;
	}
	loggit ("Added $added, skipped $skipped categories");
}

sub addLinks {
	my $links = shift;
	my ($added, $skipped) = (0,0);
	my ($taxonomy_id, $count) = runSelSQL (
					"SELECT tt.term_taxonomy_id, tt.count
					FROM wp_${blogid}term_taxonomy AS tt, wp_${blogid}terms AS t 
					WHERE t.name='Blogroll' 
					AND tt.term_id = t.term_id 
					AND tt.taxonomy='link_category'");
	$taxonomy_id || return;

	foreach my $name (keys %$links) {
		if ( (runSelSQL ("SELECT COUNT(*) FROM wp_${blogid}links WHERE
						 link_url=? AND link_name=?", $links->{$name}, $name))[0]) {
			loggit ("Link exists: $name", 1);
			$skipped++;
			next;
		}
		runSQL ("INSERT INTO wp_${blogid}links (link_url, link_name, link_image, link_target,
				 link_description, link_rel, link_notes, link_rss) 
				 VALUES (?, ?, '', '', '', '', '', '')", $links->{$name}, $name);
		my $insert_id = $DBH->last_insert_id(undef, undef, 'wp_${blogid}links', 'link_id');
		runSQL ("INSERT INTO wp_${blogid}term_relationships (object_id, term_taxonomy_id) VALUES (?,?)", $insert_id, $taxonomy_id);
		$count++;
		$added++;
	}
	$added && runSQL ("UPDATE wp_${blogid}term_taxonomy SET count=? WHERE term_taxonomy_id=?", $count, $taxonomy_id);
	loggit ("Added $added, skipped $skipped links");
}

sub runSelSQL {
	my $sql = shift;
	loggit (qq{SQL:"$sql"}, 2);
	@_ && loggit (qq{ARGS:"@_"}, 3);
	my $sth = $DBH->prepare($sql) or die $DBH->errstr;
	$sth->execute(@_);
	my @arr = $sth->fetchrow_array;
	$sth->finish;
	return @arr;
}

sub runSQL {
	my $sql = shift;
	loggit (qq{SQL:"$sql"}, 2);
	@_ && loggit (qq{ARGS:"@_"}, 3);
	my $sth = $DBH->prepare($sql) or die $DBH->errstr;
	$sth->execute(@_);
}

sub dropDatabase {
	runSQL ("DROP DATABASE $OPTS{database}");
}

sub createDatabase {
	defined $OPTS{wp_password} or error_exit "need -wp_password to specify password";

	runSQL("CREATE DATABASE $OPTS{database}");
	runSQL("GRANT ALL PRIVILEGES ON $OPTS{database}.* to '$OPTS{wp_username}'\@'localhost' 
			IDENTIFIED BY ?", $OPTS{wp_password});
	runSQL("FLUSH PRIVILEGES");
}

sub dbConnect {
	my $database = shift;
	my $password = $OPTS{password};

	# Connect to the database.
	if (!defined $password) {
		$password = '';
	}
	elsif ($password eq '') {
		# empty password supplied - prompt for value
		print "password: ";
	    system 'stty', '-echo';
		chomp ($password = <>);
		system 'stty', 'echo';
		print "\n";
	}
	$DBH = DBI->connect("DBI:mysql:database=$database:host=$OPTS{host}", 
					"$OPTS{user}", "$password",
					{'RaiseError' =>1});
}

package WordPressImport;

use strict;
use warnings;

sub new {
    my ($class, $dir) = @_;
    my $self = {
		categories => {},
		links => {},
		static => [],
		blocks => [],
		posts => [],
    };

    bless $self, $class;
	$self->import_dir($dir);
    return $self;
}

sub parse_fields {
	my ($h, $file, $str) = @_;
	if($file =~ /\.gz$/i) {
		open IN, "gunzip -c $file |" or die "Cannot gunzip -c $file:$!";
	} else {
		open IN, $file or die "Cannot open $file:$!";
	}
	local $/;
	$_=<IN>;
	close IN;
	while ( s/^([a-zA-Z]+)\|(.*?)(\||$)//s) {
		my ($p, $v) = ($1, $2);
		$p =~ /$str/ and $h->{lc $p} = qq{$v};
	}
}

sub parse_legacy_fields {
    # Old format (pre-0.4.6.1) entries have no key words (bit of a hack)
    my ($h, $file,$f1, $f2) = @_;
    open IN, $file or die "Cannot open $file:$!";
    local $/;
    $_=<IN>;
    close IN;
    ($h->{$f1}, $h->{$f2}) = /^(.*)\|\d+\|(.*)$/s;
}


sub num_posts {
	my $self = shift;
	return scalar @{$self->{posts}};
}

sub get_posts {
	my $self = shift;
	return $self->{posts}
}

sub get_static {
	my $self = shift;
	return $self->{static}
}


sub get_categories {
	my $self = shift;
	return $self->{categories};
}

sub get_links {
	my $self = shift;
	return $self->{links};
}

sub get_blocks {
	my $self = shift;
	return $self->{blocks};
}

sub get_category {
	my ($self, $index) = @_;
	$self->{categories}{$index} || die "bad category";
	return $self->{categories}{$index};
}

sub import_dir {
    my ($self, $dir) = @_;
    local(*DIR);
    opendir (DIR, $dir) or die "Cannot open dir $dir: $!";
    foreach (sort grep !/^\.+$/, readdir(DIR)) {
        -d "$dir/$_"             && $self->import_dir ("$dir/$_");
        /^(entry[\d-]+)\.txt(.gz)?$/   && $self->add_post("$dir/$1", "$2");
        /^categories\.txt$/      && $self->add_category("$dir/$_");
		/^static[\d-]+(\.txt(\.gz)?)?$/ && $self->add_static("$dir/$_");
		/^blocks\.txt$/          && $self->add_blocks("$dir/$_");
		/^links\.txt$/           && $self->add_links("$dir/$_");
    }
}

sub format_date {
	my ($s) = @_;
	my ($year, $month, $day, $hour, $min, $sec) = ($s =~ /\/.*(\d\d)(\d\d)(\d\d)-(\d\d)(\d\d)(\d\d)/);
	return "20$year-$month-$day $hour:$min:$sec"; # Y2K compliant ish...
}

sub sanitize {
	my ($s) = shift;
	no warnings;
	$$s =~ s/\[(\/)?b\]/<$1strong>/g;
	$$s =~ s/\[(\/)?i\]/<$1em>/g;
	$$s =~ s/\[url=(.*) new=.*\](.*)\[\/url\]/<a href="$1">$2<\/a>/g;
	$$s =~ s/\[img=(.*)\]/<img src=$1\/>/g;
	if ( $$s =~ s/\[[\/]?html\]//g) {
		$$s =~ s/&lt;/</g;
		$$s =~ s/&gt;/>/g;
		$$s =~ s/&quot;/"/g;
	}
}

sub add_static {
	my ($self, $file) = @_;
	push @{$self->{static}}, WordPressImport::Static->new ($file);
}

sub add_post {
	my ($self, $dir, $gz) = @_;

	# Get post
	my $post = WordPressImport::Post->new("${dir}.txt${gz}");

	# Get ratings and comments
	$post->add_data($dir,$gz);
	
	# Store post
	push @{$self->{posts}}, $post;
}

sub add_links {
	my ($self, $file) = @_;
	open IN, $file or die "Cannot open $file:$!";
	my @arr=split(/\|/s, <IN>);
	for (my $i=0; $i<= $#arr; $i += 2) { 
		$self->{links}{$arr[$i]} = $arr[$i +1];
	}
	close IN;
}

sub add_blocks {
	my ($self, $file) = @_;
	open IN, $file or die "Cannot open $file:$!";
	local $/;
	$_=<IN>;
	close IN;	
	my @arr=split(/\|/s);
	for (my $i=0; $i<= $#arr; $i += 2) { 
		push @{$self->{blocks}}, WordPressImport::Block->new ($arr[$i], $arr[$i +1]);
	}
}


sub add_category {
	my ($self, $file) = @_;
	open IN, $file or die "Cannot open $file:$!";
	local $/;
	$_=<IN>;
	close IN;
	$self->{categories}{$1}=$2 while (s/^(\d+)\|([\w ]+)\|\d+\|?//);
}

sub print_categories {
	my ($self) = shift;
	foreach (keys %{$self->{categories}}) {
		print "$_ : $self->{categories}{$_}\n";
	}
}

package WordPressImport::Post;

sub new {
    my ($class, $file) = @_;
    my $self = {
		date => undef,
		subject => undef,
		categories => undef,
		content => undef,
		comments => [],
		points => undef,
		votes => undef,
    };
    bless $self, $class;
	$self->{date} = WordPressImport::format_date ($file);
	WordPressImport::parse_fields ($self, $file, "SUBJECT|CONTENT|CATEGORIES");	
	$self->{content} || WordPressImport::parse_legacy_fields ($self, $file, "subject", "content");
	$self->{categories} ||=0; 		# Account for no category in post (seen once)
	# A nasty kludge - but accommodate for posts with multiple categories
	# by redefining categories as an array. Yuk.
	# $self->{categories} = split(/,/, $self->{categories});
	my $data = $self->{categories};
	my @values = split(/,/, $data);
	# Make sure we always have an array
	# XXX: I don't think this works anymore...
	if (ref(@values) eq 'ARRAY') {
		$self->{categories} = @values;
	} else {
		$self->{categories} = [ $self->{categories} ];
	}
	WordPressImport::sanitize (\$self->{content});
    return $self;
}

sub num_comments {
	my ($self) = shift;
	return scalar @{$self->{comments}};
}

sub get_comments {
	my ($self) = shift;
	return $self->{comments};
}

sub add_comments {
	my ($self, $dir, $gz) = @_;
	-d $dir || return;
	local(*DIR);
	opendir (DIR, $dir) or die "Cannot open dir $dir: $!";
	foreach (grep /\.txt$gz$/, readdir(DIR)) {
		push @{$self->{comments}}, WordPressImport::Comment->new ("$dir/$_");
	}
}

sub add_rating {
	my ($self, $file) = @_;
	WordPressImport::parse_fields ($self, $file, "points|votes");
	$self->{points} || die "no points";
	$self->{votes} || die "no votes";
}

sub add_data {
	my ($self, $dir, $gz) = @_;
	-d $dir || return;
	local(*DIR);
	my $cm;
	opendir (DIR, $dir) or die "Cannot open dir $dir: $!";
	foreach (grep !/^\.+$/, readdir(DIR)) {
		/^comments$/   && $self->add_comments("$dir/$_", $gz);
		/^rating.txt$/ && $self->add_rating("$dir/$_");
	}
}

package WordPressImport::Comment;

sub new {
    my ($class, $file) = @_;
    my $self = {
		date => undef,
		name => undef,
		content => undef,
		email => "",
		url => "",
    };
    bless $self, $class;
	$self->{date} = WordPressImport::format_date($file);
	my $newdate = WordPressImport::format_date($file);
	WordPressImport::parse_fields ($self, $file, "NAME|CONTENT|EMAIL|URL");
	$self->{content} || WordPressImport::parse_legacy_fields ($self, $file, "name", "content");
	WordPressImport::sanitize (\$self->{content});
    return $self;
}

package WordPressImport::Static;
sub new {
    my ($class, $file) = @_;
    my $self = {
		date => undef,
		subject => undef,
		content => undef,
    };
    bless $self, $class;
	$self->{date} = WordPressImport::format_date($file);
	WordPressImport::parse_fields ($self, $file, "SUBJECT|CONTENT");
	$self->{content} || WordPressImport::parse_legacy_fields ($self, $file, "subject", "content");
	WordPressImport::sanitize (\$self->{content});
    return $self;
}

package WordPressImport::Block;
sub new {
    my ($class, $subject, $content) = @_;
    my $self = {
		subject => undef,
		content => undef,
    };
    bless $self, $class;
	$self->{subject} = $subject;
	$self->{content} = $content;
	WordPressImport::sanitize (\$self->{content});
    return $self;
}

1