I am trying to work on user input such as
- foo
- wikt:foo
- Bar#hi there
to obtain a https link for the input, such as
- https://en.wikipedia.org/wiki/foo
- https://en.wiktionary.org/wiki/foo
- https://en.wikipedia.org/wiki/Bar#hi_there
I am trying to do this in a least manual, most clean possible way, so I can upload my script somewhere and show it to people without being ashamed of its low quality. This means:
- If I obtain an http link instead of https I would rather not hardcode a
s/^http/^https/substitution. - If I obtain an incomplete link I would rather not use regex to add missing things to it.
So far I have found two solutions but each of them has flaws.
Parse query
Run parse query on {{canonicalurl:user_input_here}} using canonicalurl magic word. It gives only http, not https links however.
#!/usr/bin/perl
use strict;
use warnings;
use MediaWiki::API;
use Data::Dumper;
my $mw = MediaWiki::API->new();
$mw->{config}->{api_url} = 'https://en.wikipedia.org/w/api.php';
my $info_ref = $mw->api ( {
action => 'parse',
prop => 'text',
text => '{{canonicalurl:Hello}}',
} ) or die $mw->{error}->{code} . ': ' . $mw->{error}->{details};
my $html = $info_ref->{parse}{text}{'*'};
print Dumper $html;
Info query
Use info query. However it does not work for sections, i.e. "Foo#bar" input will get output linking to "Foo".
#!/usr/bin/perl
use strict;
use warnings;
use MediaWiki::API;
my $mw = MediaWiki::API->new();
$mw->{config}->{api_url} = 'https://en.wikipedia.org/w/api.php';
sub get_url_by_title(){
my $title = shift;
my $info_ref = $mw->api ( {
action => 'query',
prop => 'info',
inprop => 'url',
iwurl => 1,
titles => $title,
} ) or die $mw->{error}->{code} . ': ' . $mw->{error}->{details};
if (exists $info_ref->{query}{pages}){
return (values $info_ref->{query}{pages})[0]{'fullurl'};
}
elsif (exists $info_ref->{query}{interwiki}){
return (values $info_ref->{query}{interwiki})[0]{'url'};
}
}