-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathUrlUtil.pm
executable file
·2004 lines (1591 loc) · 51.5 KB
/
UrlUtil.pm
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
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package UrlUtil;
# Utility class for common functions with URLs and HTML.
#
# Created by Frank McCown
#
# v 1.0 2006-05-01 Initially created.
# v 1.1 2007-01-20 Added functionality to NormalizeUrl to convert all
# hex-encoded characters (%XX) not in query string to
# standard ISO-8859-1 chars. Also converted spaces to +.
# v 1.2 2007-11-01 Improved hex encoding.
# v 1.3 2008-01-08 Tested for empty base and removed conversion of / in
# in Windows filenames.
# v 1.4 2011-11-05 Justin added HTML 5 tags
# Basic interface is Load & Dump
@EXPORT = qw(NormalizeUrl RemoveDotSegments GetPortNumber
ConvertUrlsToRelative RewriteSpecialUrls);
# Export groups
%EXPORT_TAGS = (all => [qw(NormalizeUrl RemoveDotSegments GetPortNumber
ConvertUrlsToRelative GetCanonicalUrl IsHtmlUrl
GetUrlPieces RemoveFilenameFromUrl ExtractLinks
GetDirName GetFileExtension RewriteSpecialUrls)]);
use strict;
use URI::URL;
use HTML::Parser;
use HTML::TagParser;
############################################################################
sub NormalizeUrl {
# Input: URL to be modified
# Returns: Modified URL or empty string if URL doesn't begin with http://
# or https://
#
# Several modifications are made to a URL:
# - Add '/' if missing at end of domain name
# http://foo.org -> http://foo.org/
# - Replace https with http
# https://foo.org/ -> http://foo.org/
# - Remove the fragement (section link) from a URL
# http://foo.org/bar.html#section1 -> http://foo.org/bar.html
# - Remove :80 from URL
# http://foo.org:80/bar.html -> http://foo.org/bar.html
# - Remove all instances of '/../' and '/./' from URL by collapsing it
# http://foo.org/../a/b/../bar.html -> http://foo.org/a/bar.html
# - Remove multiple occurrences of slash in URL (not including query string)
# http://foo.org//a///b -> http://foo.org/a/b
# - Remove '?' from end of URL if it is by itself
# http://foo.org/bar.html? -> http://foo.org/bar.html
# - Convert the URL host and TLD to lower case
# http://FOO.ORG/BAR.html -> http://foo.org/BAR.html
# - Convert all spaces before query string to +
# http://foo.org/2004 page%201.htm -> http://foo.org/2004+page+1.htm
# - Convert all hex-encoded characters (%XX) in the range [0x21 to 0x7E]
# (excluding the query string) to standard ISO-8859-1 (Latin 1) chars and
# capitalize the remaining hex chars
# http://foo.org/%7Ebar/a%20b/?test=g%8a -> http://foo.org/~bar/a+b/?test=g%8A
# - Convert '&' in query string to '&'
# - Remove common session IDs
# http://foo.org/?id=1jsessionid=999A9EF028317A82AC83F0FDFE59385A ->
# http://foo.org/?id=1
my $url = shift;
if (!defined $url) {
warn "Undefined url";
return '';
}
if ($url !~ m|^(https?://)|) {
warn "URL [$url] does not start with http:// or https://";
return '';
}
# WARNING: canonical function (thru URI obj) converts http://foo.org/%7b.jpg to
# http://foo.org/%7B.jpg. This uppercasing of chars with preceeding % char
# is a problem, so we must write our own code to parse the URL!
# This appears in http://otago.settlers.museum.
# http://otago.settlers.museum/exhibitionimages/%7b6373693D-CF52-4D34-AA95-82BFE504BD9A%7d.jpg
# Get rid of https
$url =~ s|^https|http|;
# Add / at end of domain name if missing
if ($url =~ m|^http://[^/]+$|) {
$url = "$url/";
}
# Remove :80 (default port)
$url =~ s|^(http://[^/]+):80/|$1/|;
#print "url=$url\n";
# Make sure domain name is lowercase
my ($domain) = $url =~ m|^http://([^/]+?)(:\d+)?/|;
if (!defined $domain) {
warn "Domain cannot be found in URL [$url]";
return '';
}
elsif ($domain !~ m|^[\w\-\.]+$|) {
warn "Domain [$domain] contains invalid characters from URL [$url]";
return '';
}
else {
#print "domain=$domain\n";
my $domain_lc = lc $domain;
$url =~ s|(^http://)$domain|$1$domain_lc|;
}
# Get rid of fragement
$url =~ s/#.*$//;
# Remove '/../' from URL
$url = CollapseUrlPath($url);
# Remove multiple occurances of slash in URL (not including query string)
# NOTE: Do not remove double slashes in IA urls (http://.../http://....)
my ($qs) = $url =~ m|\?(.+)$|;
#print "url=$url\nqs=$qs\n" if (defined $qs);
# Remove query string for now
$url =~ s|\?.*$||;
my ($pre) = $url =~ m|^(http://)|;
# Remove prefix from url
$url =~ s|^$pre||;
# Convert spaces to +
$url =~ s|\s|\+|g;
# Replace // with / until entire string is just /
# Make sure we don't convert http:// to http:/ for IA urls
while ($url =~ m|[^:]//|) {
$url =~ s|([^:])//|$1/|;
}
# Convert all hex-encoded characters (%XX) to standard ISO-8859-1 characters
# See list at http://www.utoronto.ca/webdocs/HTMLdocs/NewHTML/iso_table.html
# For testing purposes
my $special_url = 0;
if ($url =~ m|.*test*|) {
#if ($url =~ m|.*2f.*|) {
$special_url = 1;
print "special url [$url]\n";
}
while ($url =~ m|%([a-f0-9][a-f0-9])|ig) {
my $found = $1;
my $hex = $found;
$found = "%$found";
$hex = hex("0x$hex");
# Ignore chars outside [0x21-0x7E] and 0x2f which is '/'
if ($hex >= 0x21 && $hex <= 0x7e && $hex != 0x2f) {
$hex = chr($hex);
$url =~ s|$found|$hex|g;
#print "true: " . $hex . "\n";
}
elsif ($found eq '%20') {
#print "Convert space\n";
$url =~ s|$found|+|g;
}
else {
if ($special_url) {
print "converting to caps\n";
}
#warn "Unexpected char [$found] in URL [$url]. Changing to blank.";
#$url =~ s|$found||g;
# Capitalize %c3 -> %C3
my $cap = uc $found;
if ($cap ne $found) {
$url =~ s|$found|$cap|g;
}
}
}
# Put url back together
$url = $pre . $url;
if (defined $qs) {
# Convert any remaining '?' chars to '%3F'
$qs =~ s|\?|%3F|g;
# Convert all '&' to '&'
$qs =~ s|&|&|g;
# Strip session IDs
$qs = StripSessionIds($qs);
# Remove any initial '&', terminating '&' and multiple occurances of '&'
# right next to each other.
$qs =~ s|^&+||;
$qs =~ s|&+$||;
$qs =~ s|&&|&|g;
# Capitalize all remaining hex chars in query string
while ($qs =~ m|%([a-f0-9][a-f0-9])|ig) {
my $found = "%$1";
my $cap = uc $found;
if ($cap ne $found) {
$qs =~ s|$found|$cap|g;
}
}
$url .= "?$qs" if length $qs > 0;
}
return $url;
}
############################################################################
sub CollapseUrlPath {
# Removes '..' and '.' from URLs using rules from rfc3986
# NOTE: We must avoid using the URI::URL object because it will
# escape/unescape chars that we may not really want converted.
my $url = shift;
# Get everything after the scheme
#my $path = $url_o->full_path;
my ($before_path, $path) = $url =~ m|^(https?://[^/]+)(/.+)$|;
if (!defined $path) {
return $url;
}
#print "before_path=$before_path\n";
#print "path=$path\n";
$path = RemoveDotSegments($path);
$url = "$before_path$path";
return $url;
}
############################################################################
sub RemoveDotSegments
{
# Collapse the path of a URL using the rules established in rfc3986.
# See http://rfc.net/rfc3986.html#s5.2.4.
# This function is from http://www.gbiv.com/protocols/uri/rev-2002/uri_test.pl
# and is in the public domain. By Roy T. Fielding
local($_) = @_; # Path should begin with /
my $buf = "";
while ($_) {
# remove any prefix of "../" or "./"
#
next if s/^\.\.?\///;
# replace any prefix segment of "/./" or "/." with "/"
#
next if s/^\/\.(\/|$)/\//;
# replace any prefix segment of "/../" or "/.." with "/"
# and remove the last segment added to buffer (if any)
#
if (s/^\/\.\.(\/|$)/\//) {
$buf =~ s/\/?[^\/]*$//;
next;
}
# remove a trailing dot-segment if nothing else is left
last if s/^\.\.?$//;
# otherwise, remove the first segment and append it to buffer
#
s/^(\/?[^\/]*)//;
$buf .= $1;
}
return $buf;
}
############################################################################
sub ConvertUrlToLowerCase {
# Convert URL (not including qeuery string) to lower case
my $url = shift;
my ($u, $qs) = $url =~ m|(^.+)\?(.+)|;
if (defined $qs) {
#print "\n\nQUERY STRING: [$qs]\n\n";
$u = lc $u;
$url = "$u?$qs";
}
else {
$url = lc $url;
}
return $url;
}
############################################################################
sub GetPortNumber {
# Returns the port number for the URL
my $url = shift;
my $url_o = URI::URL->new($url);
return $url_o->port;
}
############################################################################
sub StripSessionIds {
# Removes common session IDs from the query string of a URL.
# Much of the information about session IDs was obtained from Hertrix's
# StripSessionIds class.
my $qs = shift;
# Remove JSP and PHP session IDs including possible '&' in front. Examples:
# jsessionid=999A9EF028317A82AC83F0FDFE59385A
# PHPSESSID=9682993c8daa2c5497996114facdc805
#print "qs=$qs\n";
if ($qs =~ s/&?(jsessionid|phpsessid)=[0-9a-z]{32}(&.*)?$//i) {
$qs .= $2 if defined $2;
}
# Usually occurance of sid= followed by 32 byte string is a session id.
# Remove sid *after* removing PHPSESSID since the reg ex would match
# Example: sid=9682993c8daa2c5497996114facdc805
if ($qs =~ s/&?sid=[0-9a-z]{32}(&.*)?$//i) {
$qs .= $1 if defined $1;
}
# Remove ASP session IDs
# Example: ASPSESSIONIDAQBSDSRT=EOHBLBDDPFCLHKPGGKLILNAM
if ($qs =~ s/&?ASPSESSIONID[a-zA-Z]{8}=[a-zA-Z]{24}(&.*)?$//i) {
$qs .= $1 if defined $1;
}
return $qs;
}
############################################################################
sub GetCanonicalUrl {
# Return the canonical url that will be used to refer to the same url.
# Example: Both these urls have the same canonical url:
# http://foo.org/%7B6%2DC.jpg
# canoncial = http://foo.org/%7B6-C.jpg
# http://foo.org/%7b6-C.jpg
# canoncial = http://foo.org/%7B6-C.jpg
my $url = shift;
my $url_o = new URI::URL $url;
return $url_o->canonical;
}
############################################################################
sub WindowsConvertFilePath {
my $path = shift;
my $debug = shift; # Set to 1 if wanting to print debug info
# Convert file path to use Windows acceptable chars. Example:
# www.xemacs.org:4300/search.pl?input=blah&test=<>|"*
# converts to
# www.xemacs.org+4300\search.pl@input=blah&test=%3C%3E%7C%22%2A
# Windows won't allow \, |, /, :, ?, ", *, <, > in the filename
# use @ instead of ? to separate the query string and + instead of : for port
# use hex value form other chars %HH
my $old_path = $path;
$path = WindowsConvertUrlPath($path);
# It's not necessary to convert / to \ because it is done automatically by catfile in warrick.pl
#$path =~ s|/|\\|g;
if ($old_path eq $path) {
print "WindowsConvertFilePath: No change to path\n" if $debug;
}
else {
print "WindowsConvertFilePath: changed [$old_path] to [$path]\n" if $debug;
}
return $path;
}
############################################################################
sub WindowsConvertUrlPath {
my $path = shift;
my $debug = shift; # Set to 1 if wanting to print debug info
# Convert URL path to use Windows acceptable chars. Example:
# http://www.xemacs.org:4300/search.pl?input=blah&test=<>|"*
# converts to
# http://www.xemacs.org+4300\search.pl@input=blah&test=%3C%3E%7C%22%2A
# Windows won't allow \, |, /, :, ?, ", *, <, > in the filename
# use @ instead of ? to separate the query string and + instead of : for port
# use hex value form other chars %HH
my $old_path = $path;
my $prefix;
# See if this is a relative or absolute URL and pick off http:// part
if ($path =~ m|(https?://)(.+)$|) {
$prefix = $1;
$path = $2;
}
# Get query string if it is present
if ($path =~ m|(.+)\?(.+)$|) {
$path = $1;
my $query_string = $2;
#print "path=[$path]\nqs=[$query_string]\n";
# Replace all / slashes with _
$query_string =~ s|/|_|g;
# Escape all \ slashes
$query_string =~ s/\\/%5C/g;
# Replace '?' with '@'
$path = $path . '@' . $query_string;
}
$path =~ s/\|/%7C/g;
$path =~ s/\:/+/g;
$path =~ s/\"/%22/g;
$path =~ s/\*/%2A/g;
$path =~ s/</%3C/g;
$path =~ s/>/%3E/g;
# Put http:// back on front
$path = $prefix . $path if defined $prefix;
if ($old_path eq $path) {
print "WindowsConvertUrlPath: No change to path\n" if $debug;
}
else {
print "WindowsConvertUrlPath: changed [$old_path] to [$path]\n" if $debug;
}
return $path;
}
############################################################################
sub UnixConvertPath {
my $path = shift;
# RIGHT NOW THIS FUNCTION DOES NOTHING.
# convert path to use Unix acceptable chars. Example:
# www.xemacs.org:4300/~user/search.pl?input=blah&test=<>|"*
# converts to
# www.xemacs.org+4300:/search.pl@input=blah&test=%3C%3E%7C%22%2A
# Unix won't allow ~ in the filename
# use hex value form chars %HH
# NOTE: IE and Firefox will convert "%7E" into "~" when browsing on-line,
# so we can't convert the chars and allow the user to view the files
# on-line. Therefore just ignore it for now.
#$path =~ s/\~/%7E/g;
return $path;
}
############################################################################
sub IsHtmlUrl {
# Returns 1 if URL ends with '/', '.html', '.htm', '.shtml', ".php",
# ".jsp", or ".asp" and does not have a query string. Returns 0 otherwise.
my $url = shift;
if ($url !~ m|\?| && ($url =~ m|/$| || $url =~ m|\.s?html?$|i ||
$url =~ m|\.php$|i || $url =~ m|\.jsp$|i || $url =~ m|\.asp$|i)) {
return 1;
}
else {
return 0;
}
}
############################################################################
sub IsMissingFileExtension {
# Returns 1 if URL is not a query string and does not contain a file
# extension.
#
# Examples: http://foo.org/ returns 1
# http://foo.org/abc returns 1
# http://foo.org/abc. returns 1
# http://foo.org/abc.html returns 0
# http://foo.org/abc.HTM returns 0
my $url = shift;
if (GetFileExtension($url) eq "") {
return 1;
}
else {
return 0;
}
}
############################################################################
sub GetFileExtension {
# Returns the file extension of a URL or an empty string if one does
# not exist. Returns empty string for URLs with a query string.
# The file extension is all characters after the period.
#
# Examples: http://foo.org/ returns ""
# http://foo.org/abc returns ""
# http://foo.org/abc. returns ""
# http://foo.org/abc.html returns "html"
# http://foo.org/abc.HTM returns "HTM"
my $url = shift;
my $ext = "";
if ($url !~ m|\?|) {
($ext) = $url =~ m|/.+\.([^./]+)$|;
$ext = "" if !defined $ext;
}
return $ext;
}
############################################################################
# Construct a hash of tag names that may have links.
my %Link_attr;
{
# To simplify things, reformat the %HTML::Tagset::linkElements
# hash so that it is always a hash of hashes.
require HTML::Tagset;
while (my($k,$v) = each %HTML::Tagset::linkElements) {
if (ref($v)) {
$v = { map {$_ => 1} @$v };
}
else {
$v = { $v => 1};
}
$Link_attr{$k} = $v;
#print "$k=$v\n";
}
# Add meta tag which is not included in %HTML::Tagset::linkElements
# so we can later catch <meta http-equiv="refresh" content="2;URL=/new.html">
my $attr = {content => 1};
$Link_attr{meta} = $attr;
# Uncomment this to see what HTML::Tagset::linkElements thinks are
# the tags with link attributes
#use Data::Dump; Data::Dump::dump(\%Link_attr); exit;
}
############################################################################
sub ExtractLinks {
# Return an array of all links in the given HTML
my $html = $_[0]; # Text of html document
my $doc_url = $_[1]; # URL of html document
# Set the base URL
my $base = $doc_url;
# Store all links we find
my @found_links = ();
# Tags and attributes that contain links
my %tags = qw(
a href
A href
img src
link href
body background
frame src
iframe src
ilayer background
script src
area href
form action
base href
table background
td background
tr background
th background
meta content
);
my @html_text = ();
# Set up the parser.
my $p = HTML::Parser->new(api_version => 3);
#$p->handler(default => sub { print @_ }, "text");
$p->handler(default => sub { push(@html_text, @_) }, "text");
# All links are found in start tags. This handler will evaluate
# &edit for each link attribute found.
$p->handler(start => sub {
my ($tagname, $pos, $text) = @_;
if (my $link_attr = $Link_attr{$tagname}) {
while (4 <= @$pos) {
# use attribute sets from right to left
# to avoid invalidating the offsets
# when replacing the values
my($k_offset, $k_len, $v_offset, $v_len) =
splice(@$pos, -4);
my $attrname = lc(substr($text, $k_offset, $k_len));
next unless $link_attr->{$attrname};
next unless $v_offset; # 0 v_offset means no value
my $v = substr($text, $v_offset, $v_len);
$v =~ s/^([\'\"])(.*)\1$/$2/;
if (defined $tags{$tagname} && $tags{$tagname} eq $attrname) {
#print "v=$v\n";
# See if a BASE tag is present- it overrides the given base
if ($tagname eq 'base' && $attrname eq 'href' && $v ne '') {
$base = $v;
}
elsif ($tagname eq 'meta' && $attrname eq 'content') {
# Pull off link portion from "2;URL=/splashpage.html"
# It's possible the meta tag does not have a
# http-equiv="refresh", but we'll grab it anyway.
if ($v =~ s|\s*\d+\s*;\s*url\s*=\s*([^\s]+)\s*$|$1|i) {
push @found_links, $v;
}
}
else {
# Save all other links
push @found_links, $v;
}
}
}
}
},
"tagname, tokenpos, text");
$p->parse($html);
# Put base onto found links
my @url_set = ();
foreach my $link (@found_links) {
my $url = URI->new($link);
my $new_url;
if (defined $base && $base ne '') {
$new_url = $url->abs($base);
}
else {
$new_url = $url;
}
#print "$new_url\n";
push @url_set, $new_url;
}
#############jbrunelle added 11/04/2011
####this is experimental, and aims to handle the HTML 5 tags.
####specifically, it will get the src attribute from the <embed> tags
####this will recover any flash movies, sounds, or other non-html
####codings that may exist in the archives, and be necessary for
####a recovery job.
##tags that may have a src element I care about:
#<source src=""> #for example, inside the video or audio tags
#<object data="">
#<embed>
if(!($doc_url =~ m/\.js$/i || $doc_url =~ m/\.css$/i || $doc_url =~ m/\.asp$/i) && ($doc_url =~ m/\.html/i || $doc_url =~ m/\.htm/i || $doc_url =~ m/\/$/i))
{
##parse the HTML and find the target tags
my $html1 = HTML::TagParser->new( $html );
my $elem1 = $html1->getElementsByTagName( "source" );
my $elem2 = $html1->getElementsByTagName( "object" );
my $elem3 = $html1->getElementsByTagName( "embed" );
for my $e (@{$elem1})
{
my $foundUri = NormalizeUrl($e->src);
&logIt("Added HTML5 $foundUri to UrlFrontier\n\n");
push(@url_set, $foundUri);
}
}
#############end addition by jbrunelle for <embed> tag
##############to handle CSS stuff
if($doc_url =~ m/\.css/i)
{
my @cssLinks = ExtractCSSLinks($html);
foreach my $cl (@cssLinks)
{
push(@url_set, $cl);
}
}
################end handle CSS stuff
# Return all links
return @url_set;
}
############################################################################
sub ExtractLinksNR {
# Return an array of all links ONLY TO PAGE REQUISITES in the given HTML
my $html = $_[0]; # Text of html document
my $doc_url = $_[1]; # URL of html document
# Set the base URL
my $base = $doc_url;
# Store all links we find
my @found_links = ();
# Tags and attributes that contain links
my %tags = qw(
img src
link href
script src
table background
td background
tr background
th background
);
my @html_text = ();
# Set up the parser.
my $p = HTML::Parser->new(api_version => 3);
#$p->handler(default => sub { print @_ }, "text");
$p->handler(default => sub { push(@html_text, @_) }, "text");
# All links are found in start tags. This handler will evaluate
# &edit for each link attribute found.
$p->handler(start => sub {
my ($tagname, $pos, $text) = @_;
if (my $link_attr = $Link_attr{$tagname}) {
while (4 <= @$pos) {
# use attribute sets from right to left
# to avoid invalidating the offsets
# when replacing the values
my($k_offset, $k_len, $v_offset, $v_len) =
splice(@$pos, -4);
my $attrname = lc(substr($text, $k_offset, $k_len));
next unless $link_attr->{$attrname};
next unless $v_offset; # 0 v_offset means no value
my $v = substr($text, $v_offset, $v_len);
$v =~ s/^([\'\"])(.*)\1$/$2/;
if (defined $tags{$tagname} && $tags{$tagname} eq $attrname) {
#print "v=$v\n";
# See if a BASE tag is present- it overrides the given base
if ($tagname eq 'base' && $attrname eq 'href' && $v ne '') {
$base = $v;
}
elsif ($tagname eq 'meta' && $attrname eq 'content') {
# Pull off link portion from "2;URL=/splashpage.html"
# It's possible the meta tag does not have a
# http-equiv="refresh", but we'll grab it anyway.
if ($v =~ s|\s*\d+\s*;\s*url\s*=\s*([^\s]+)\s*$|$1|i) {
push @found_links, $v;
}
}
else {
# Save all other links
push @found_links, $v;
}
}
}
}
},
"tagname, tokenpos, text");
$p->parse($html);
# Put base onto found links
my @url_set = ();
foreach my $link (@found_links) {
my $url = URI->new($link);
my $new_url;
if (defined $base && $base ne '') {
$new_url = $url->abs($base);
}
else {
$new_url = $url;
}
#print "$new_url\n";
push @url_set, $new_url;
}
#############jbrunelle added 11/04/2011
####this is experimental, and aims to handle the HTML 5 tags.
####specifically, it will get the src attribute from the <embed> tags
####this will recover any flash movies, sounds, or other non-html
####codings that may exist in the archives, and be necessary for
####a recovery job.
##tags that may have a src element I care about:
#<source src=""> #for example, inside the video or audio tags
#<object data="">
#<embed>
##parse the HTML and find the target tags
my $html1 = HTML::TagParser->new( $html );
my $elem1 = $html1->getElementsByTagName( "source" );
my $elem2 = $html1->getElementsByTagName( "object" );
my $elem3 = $html1->getElementsByTagName( "embed" );
for my $e (@{$elem1})
{
my $foundUri = NormalizeUrl($e->src);
&logIt("Added HTML5 $foundUri to UrlFrontier\n\n");
push(@url_set, $foundUri);
}
#############end addition by jbrunelle for <embed> tag
##############to handle CSS stuff
if($doc_url =~ m/\.css/i)
{
my @cssLinks = ExtractCSSLinks($html);
foreach my $cl (@cssLinks)
{
push(@url_set, $cl);
}
}
################end handle CSS stuff
# Return all links
return @url_set;
}
############################################################################
sub ExtractCSSLinks {
my $html = $_[0]; # Text of html document
my $doc_url = $_[1]; # URL of html document
my @lines = split("\n", $html);
my @urls;
foreach my $l (@lines)
{
if($l =~ m/url/i)
{
$l =~ s/.*url\(//i;
$l =~ s/\)//i;
$l =~ s/;//i;
$l =~ s/no-repeat//i;
$l =~ s/[0-9]*\% [0-9]//i;
$l =~ s/[0-9]*\%//i;
if($l =~ m/^\.\.\//i)
{
$l = $doc_url . "/" . $l;
}
&logIt("CSS URL found: " . NormalizeUrl($l) . "\n\n");
push(@urls, NormalizeUrl($l));
}
}
return @urls;
}
############################################################################
sub inFoundArray($)
{
#######################
#This function determines if a certain needle is in an array haystack
#more specifically, it determines if a URL currently exists in the frontier
#######################
my $needle = $_[0];
my @url_set = @{$_[1]};
for(my $i = 0; $i < $#url_set + 1; $i++)
{
my $h = $url_set[$i];
my $n = $needle;
##if we found the URL in the Array
if($h eq $n)
{
return 1;
}
}
return 0;
}
############################################################################
sub GetDirName {
# Get directory name for a URL. Returns '/' if invalid URL given.
#
# Examples: http://www.foo.edu -> /
# http://www.foo.edu/ -> /
# http://www.foo.edu/abc/ -> /abc/
# http://www.foo.edu/abc/zoo -> /abc/
# http://www.foo.edu/abc/zoo.html -> /abc/
# http://www.foo.edu/abc/?test -> /abc/
my $url = shift;
my $url_o = URI->new($url);
my $path = $url_o->path;
# Strip off filename if present
$path =~ s/[^\/]+$//;
$path = '/' if $path eq '';
return $path
}
############################################################################
sub ConvertUrlsToRelative {
# Convert all the URLs in the given HTML document to relative URLs
my $html = $_[0]; # Text of html document
my $doc_url = $_[1]; # Url of html document
#print "\n-- ConvertUrlsToRelative : Rewriting urls\n";
my $count = 0;
my $url = URI->new($doc_url);
my $url_begin = "http://" . $url->host;
#($url_begin) = ($doc_url =~ /^(http:\/\/.+)\//);
#print "url_begin=$url_begin\n";
# Convert urls from relative to absolute
my @html_text = ();
# Set up the parser.
my $p = HTML::Parser->new(api_version => 3);