JPFR.pm untested

filter: Statementstmt 0.0% 0 / 571 Branchbran 0.0% 0 / 216 Conditioncond 0.0% 0 / 34 MC/DCmcdc 0.0% 0 / 22 Subroutinesub 0.0% 0 / 51 Podpod 0.0% 0 / 32 totaltotal 0.0% 0 / 926 CC 110 SCAR 40.0
CC
110
Cov
0%
get_label_ja
210.0
load_lb_files
132.0
get_file
110.0
CRAP 54.5
1 package XBRL::JPFR;
2  
3 use base XBRL;
4  
5 use Carp;
6 use XML::LibXML;
7 use XML::LibXML::XPathContext;
8 use XBRL::JPFR::Arc;
9 use XBRL::JPFR::Context;
10 use XBRL::JPFR::Unit;
11 use XBRL::JPFR::Item;
12 use XBRL::JPFR::Schema;
13 use XBRL::JPFR::Taxonomy;
14 use XBRL::JPFR::Dimension;
15 use XBRL::JPFR::Branch;
16  
17 use LWP::UserAgent;
18 use File::Spec;
19 use Cwd;
20 use Data::Dumper;
21 use Encode;
22 use URI;
23 use Hash::Merge qw(merge);
24  
25 our $VERSION = '0.06';
26  
27 my %default = (
28 main_schema => undef,
29 schema_dir => undef,
30 taxonomy => undef,
31 contexts => {},
32 units => {},
33 items => [],
34 itemhash => {},
35 labelhash => {},
36 trees => {},
37 item_index => undef,
38 file => undef,
39 base => undef,
40 lang => 'ja',
41 only_ja => 1,
42 prefix => '',
43 schema_files => [],
44 linkbase_files => [],
45 only_items => 0,
46 std_labels => 0,
47 rolelinks_edinet => {},
48 );
49  
50 sub new() {
51 my ($class, $args) = @_;
52 my $self = merge($args, \%default);
53 bless $self, $class;
54  
55 $$self{'schema_dir'} = $$args{'schema_dir'};
56 $$self{'file'} = $$args{'file'};
57 #Check the schema dir
58 if ($$self{'schema_dir'}) {
59 if (-d $$self{'schema_dir'}) {
60 if (!-w $$self{'schema_dir'}) {
61 #the directory exists but isn't writeable
62 croak "$$self{'schema_dir'} exists but isn't writeable by this user\n";
63 }
64 }
65 else {
66 #try and create the directory
67 mkdir($$self{'schema_dir'}, 777) or croak "$$self{'schema_dir'} can't be created because: $!\n";
68 }
69 }
70 else {
71 #the schema_dir parameter wasn't there, use tmp
72 $$self{'schema_dir'} = File::Temp->newdir(cleanup => 1);
73 }
74  
75 if ($$self{'file'}) {
76 my ($volume, $dir, $filename) = File::Spec->splitpath($$self{'file'});
77 if (!$dir) {
78 my $curdir = getcwd();
79 my $full_path = File::Spec->catpath(undef, $curdir, $$self{'file'});
80 if (-e $full_path) {
81 $$self{'base'} = $curdir;
82 $$self{'fullpath'} = $full_path;
83 }
84 else {
85 croak "can't find $full_path to start processing\n";
86 }
87 }
88 else {
89 $$self{'fullpath'} = $self->{'file'};
90 $$self{'file'} = $filename;
91 $$self{'base'} = $dir;
92 }
93 }
94 else {
95 croak "XBRL::JPFR requires an existing file to begin processing\n";
96 }
97  
98 # We can overwrite parse_file if it is invoked as '$self->parse_file()', but cannot if '&parse_file($self)'
99 $self->parse_file();
100  
101 return $self;
102 }
103  
104 sub parse_file {
105 my ($self) = @_;
106  
107 if (!$$self{'fullpath'}) {
108 croak "full path not set in parse file but file is set to: $$self{'file'}\n";
109 }
110  
111 my $xc = $self->make_xpath($$self{'fullpath'}, \$$self{'prefix'});
112  
113 #load the schemas
114 # XBRL2.1: 3.2
115 # DTS rules of discovery: ONLY the followings are referenced.
116 # 1. referenced directly from an XBRL Instance using the <schemaRef> element.
117 # 2. referenced from a discovered taxonomy schema via an XML Schema import element.
118 # 3. referenced from a discovered Linkbase document via a <loc> element.
119 # 6. referenced from a discovered taxonomy schema via a <linkbaseRef> element.
120 my $s_ref = $xc->findnodes("//*[local-name() = 'schemaRef']");
121 if (!$s_ref || !@$s_ref) {
122 warn "No schemaRef($$self{'file'})";
123 #return;
124 }
125 elsif (!$$self{'only_items'}) {
126 my $schema_file = $$s_ref[0]->getAttribute('xlink:href');
127 push @{$$self{'schema_files'}}, $schema_file;
128 my $schema_path = File::Spec->catpath(undef, $$self{'base'}, $schema_file);
129 my $schema_xpath = $self->make_xpath($schema_path);
130 my $main_schema = XBRL::JPFR::Schema->new({file => $schema_file, xpath => $schema_xpath});
131 $$self{'taxonomy'} = XBRL::JPFR::Taxonomy->new({
132 main_schema => $main_schema,
133 lang => $$self{'lang'},
134 });
135 }
136  
137 if (!$$self{'only_items'}) {
138 $self->add_schemas();
139 $self->load_lb_files();
140 $$self{'taxonomy'}->select_arcs();
141 $self->set_labels();
142 $self->load_contexts($xc);
143 $self->load_units($xc);
144 }
145 $self->load_items($xc);
146 $self->create_trees();
147 }
148  
149 sub add_schemas {
150 my ($self, $other_schema_files) = @_;
151 $other_schema_files = $$self{'taxonomy'}->get_other_schemas() if !$other_schema_files;
152 while (my $other = shift @{$other_schema_files}) {
153 #Get the file
154 next if $other =~ /-rt-|_rt_/; # role type
155 my $s_file = $self->get_file($other, $$self{'schema_dir'});
156 next if !defined $s_file;
157 next if $$self{'taxonomy'}->has_schema($s_file);
158 push @{$$self{'schema_files'}}, $s_file;
159 #make the xpath
160 my $s_xpath = $self->make_xpath($s_file);
161 #add the schema
162 my $schema = XBRL::JPFR::Schema->new({file => $s_file, xpath => $s_xpath});
163 $$self{'taxonomy'}->add_schema($schema);
164 my $ns = $schema->namespace();
165 my $more_schema_files = $$self{'taxonomy'}->get_other_schemas($ns);
166 push @$other_schema_files, @$more_schema_files if @$more_schema_files;
167 }
168 }
169  
170 sub load_lb_files {
171 my ($self) = @_;
172 my $lb_files = $$self{'taxonomy'}->get_lb_files();
173 # branches from CorrectionOfConsolidatedFinancialForecastInThisQuarter is out of the main tree.
174 # this is corrected in tse-qcedjpsm-2011-06-30-presentation.xml
175 if (grep {/tse-qcedjpsm-2007-06-30-presentation\.xml/} @$lb_files) {
176 push @$lb_files, "$$self{'schema_dir'}/tse-qcedjpsm-2007-06-30-presentation-correction.xml";
177 }
178 my (@remotes, @locals);
179 for my $file_name (@$lb_files) {
180 my $file = $self->get_file($file_name, $$self{'base'});
181 if (!$file) {
182 warn "The basedir is: $$self{'base'}\nunable to get $file_name";
183 next;
184 }
185 next if $file_name =~ /_gla\.xml|reference\.xml|_ref\.xml|gla_ias|gre_ias/;
186 next if $file_name =~ /-en\.xml$|-en-/ && $$self{'only_ja'};
187 if ($file =~ /^$$self{'base'}/) {
188 push @locals, $file;
189 }
190 else {
191 push @remotes, $file;
192 }
193 }
194  
195 for my $file (@remotes, @locals) {
196 next if grep (/^$file$/, @{$$self{'linkbase_files'}});
197 push @{$$self{'linkbase_files'}}, $file;
198  
199 my $lb_xpath = $self->make_xpath($file);
200 my @link_types = (
201 'presentationLink', 'definitionLink', 'calculationLink', 'labelLink',
202 #'referenceLink',
203 );
204 foreach my $link_type (@link_types) {
205 next unless $lb_xpath->exists("//*[local-name() = '$link_type']");
206 # there can be no link if not extended.
207 my %arcs = ();
208 my $rolerefs = $lb_xpath->findnodes("//*[local-name() = 'roleRef']");
209 my @uris = $rolerefs ? map {$_->getAttribute('roleURI')} @$rolerefs : ();
210 push @uris, 'http://www.xbrl.org/2003/role/link';
211 foreach my $uri (@uris) {
212 next if !$uri;
213 my $arcs = $self->collect_arcs($link_type, $uri, $lb_xpath);
214 $arcs{$uri} = $arcs if $arcs && @$arcs;
215 }
216 my $type = substr $link_type, 0, 3;
217 $$self{'taxonomy'}->$type(\%arcs);
218 }
219  
220 }
221 }
222  
223 sub set_labels {
224 my ($self) = @_;
225 my $all_arcs = $$self{'taxonomy'}->lab();
226 my $hash = exists $$self{'labelhash'} ? $$self{'labelhash'} : ($$self{'labelhash'} = {});
227 foreach my $rolelink (keys %$all_arcs) {
228 my $arcs = $$all_arcs{$rolelink};
229 foreach my $arc (@$arcs) {
230 next unless $arc;
231 my ($lang, $rolelabel, $text, $from_short) = @$arc{'lang', 'role', 'text', 'from_short'};
232 my $xbrllabel = XBRL::JPFR::Label->new();
233 $xbrllabel->name($$arc{'from_full'});
234 $xbrllabel->role($rolelabel);
235 $xbrllabel->lang($lang);
236 $xbrllabel->value($text);
237 $xbrllabel->id($$arc{'id'});
238 $xbrllabel->label($$arc{'to_name'});
239 $$hash{$lang}{$from_short}{$rolelink}{$rolelabel} = $text;
240 push @{$$self{'taxonomy'}{'labels'}}, $xbrllabel;
241 }
242 }
243 }
244  
245 sub load_contexts {
246 my ($self, $xc) = @_;
247 my $cons = $xc->findnodes("//*[local-name() = 'context']");
248 for (@$cons) {
249 my $cont = XBRL::JPFR::Context->new(
250 $_, $$self{'labelhash'}, $$self{'prefix'},
251 {lang => $$self{'lang'}},
252 );
253 $$self{'contexts'}{$cont->id()} = $cont;
254 }
255 }
256  
257 sub load_units {
258 my ($self, $xc) = @_;
259 my $units = $xc->findnodes("//*[local-name() = 'unit']");
260 for (@$units) {
261 my $unit = XBRL::JPFR::Unit->new($_);
262 $$self{'units'}{$unit->id()} = $unit;
263 }
264 }
265  
266 sub load_items {
267 my ($self, $xc) = @_;
268 my $encoding = $xc->getContextNode()->encoding();
269 $encoding = 'UTF-8' if !$encoding;
270 my $raw_items = $xc->findnodes('//*[@contextRef]');
271 my @items = ();
272 for my $instance_xml (@$raw_items) {
273 my $item = XBRL::JPFR::Item->new($instance_xml, $encoding);
274 my $id_short = $item->name();
275 my $context = $item->contextRef();
276 $id_short =~ s/:/_/;
277 if (!$$self{'only_items'}) {
278 $self->add_element_fields($item);
279 if ($$self{'lang'} eq 'ja') {
280 if ($item->localname() =~ /ExtendedLinkRoleLabel/) {
281 # for EDINET or TDnet(edjpfr)
282 $self->add_rolelink_edinet($item->localname(), $item->value());
283 }
284 }
285 }
286 push(@items, $item);
287 if (exists $$self{'itemhash'}{$id_short}{$context}) {
288 # When contextRef="CG", we can have multi items
289 my $ref = ref $$self{'itemhash'}{$id_short}{$context};
290 if ($ref =~ /ARRAY/) {
291 push @{$$self{'itemhash'}{$id_short}{$context}}, $item;
292 }
293 else {
294 $$self{'itemhash'}{$id_short}{$context} =
295 [$$self{'itemhash'}{$id_short}{$context}, $item];
296 }
297 }
298 else {
299 $$self{'itemhash'}{$id_short}{$context} = $item;
300 }
301 }
302 $$self{'items'} = \@items;
303  
304 #create the item lookup index
305 # CAVEAT: the name and the contextRef will not definitely decide it's item, mentioned above.
306 my %index = ();
307 for (my $j = 0; $j < @items; $j++) {
308 $index{$items[$j]->name()}{$items[$j]->contextRef()} = $j;
309 }
310 $$self{'item_index'} = \%index;
311 }
312  
313 sub add_element_fields {
314 my ($self, $item) = @_;
315 my $id_short = $item->prefix(). "_". $item->localname();
316 if (exists $$self{'taxonomy'}{'elements'}{$id_short}) {
317 my $ele = $$self{'taxonomy'}{'elements'}{$id_short};
318 add_fields_to_item($item, $ele);
319 return;
320 }
321 else {
322 my $item_ns = $item->namespace();
323 my $schema = $$self{'taxonomy'}{'schemas'}{$item_ns};
324 my $id = "$item_ns/". $item->localname();
325 if (exists $$schema{'elements'}{$id}) {
326 my $ele = $$schema{'elements'}{$id};
327 add_fields_to_item($item, $ele);
328 return;
329 }
330 }
331 croak "No element($id_short)\n".Dumper($item);
332 }
333  
334 sub add_fields_to_item {
335 my ($item, $ele) = @_;
336 foreach (qw(type nillable periodType subGroup substitutionGroup)) {
337 $item->$_($ele->$_());
338 }
339 #
340 # grep 'type=".*percent.*' *.xsd | sed -e 's/.*\(type="[^ ]*"\).*/\1/' |sort |uniq
341 #
342 # TDnet
343 # type="tse-cm-cg:percentageOfSharesHeldByForeignInvestorsItemType"
344 # type="tse-ed-types:percentage1ItemType"
345 # type="tse-ed-types:percentage2ItemType"
346 # type="tse-types-ed:percentage1ItemType"
347 # type="tse-types-ed:percentage2ItemType"
348 # tse-t-cg_OwnershipInterest -- type="xbrli:pureItemType"
349 # EDINET
350 # type="num:percentItemType"
351 # jpcrp_cor_PriceEarningsRatioSummaryOfBusinessResults -- type="xbrli:decimalItemType"
352 # jpcrp_cor_AverageNumberOfTemporaryWorkers -- type="xbrli:decimalItemType"
353 # jpcrp_cor_PriceEarningsRatioUSGAAPSummaryOfBusinessResults -- type="num:percentItemType"
354 #
355 my $name = $item->name();
356 if ($ele->type() =~ /percent/ && $name !~ /PriceEarningsRatio/) {
357 if (!defined $item->scale()) {
358 $item->adjust_percent();
359 }
360 }
361 if ($name eq 'tse-t-cg:OwnershipInterest') {
362 if (!defined $item->scale()) {
363 $item->adjust_percent();
364 }
365 }
366 }
367  
368 sub collect_arcs {
369 my ($self, $type, $uri, $xpath) = @_;
370 my $encoding = $xpath->getContextNode()->encoding();
371 $encoding = 'UTF-8' if !$encoding;
372 my $section = $xpath->findnodes("//*[local-name() = '$type'][\@xlink:role = '$uri']");
373 return undef unless $section;
374  
375 my (@loc_links, @lab_links, @arc_links);
376 $type =~ s/Link$/Arc/g;
377 for my $node (@{$section}) {
378 push(@lab_links, $node->getChildrenByLocalName('label')) if $type =~ /^lab/;
379 push(@loc_links, $node->getChildrenByLocalName('loc'));
380 push(@arc_links, $node->getChildrenByLocalName($type));
381 }
382  
383 my (%locs, %labs);
384 foreach my $link (@loc_links) {
385 my $label = $link->getAttribute('xlink:label');
386 push @{$locs{$label}}, $link;
387 }
388 foreach my $link (@lab_links) {
389 my $label = $link->getAttribute('xlink:label');
390 # same labels and different roles
391 # 2009/S0005C0M/jpfr-asr-E00351-000-2009-12-31-01-2010-03-30-label.xml
392 # XBRL2.1: 3.5.3.8.2
393 # Several resources in an extended link MAY have the same label.
394 push @{$labs{$label}}, $link;
395 }
396  
397 my @arcs;
398 for my $link (@arc_links) {
399 my $arcs = make_arcs($link, \%locs, \%labs, $encoding);
400 next if !$arcs || !@$arcs;
401 $self->check_arc_elements($arcs, \%labs);
402 push @arcs, @$arcs;
403 }
404 return \@arcs;
405 }
406  
407 sub make_arcs {
408 my ($link, $locs, $labs, $encoding) = @_;
409 my $to_locs = %$labs ? $labs : $locs;
410 my $from_locs = $locs;
411 my $to_name = $link->getAttribute('xlink:to');
412 my $from_name = $link->getAttribute('xlink:from');
413 return undef if !exists $$to_locs{$to_name};
414 return undef if !exists $$from_locs{$from_name};
415 my $to_locs2 = $$to_locs{$to_name};
416 my $from_locs2 = $$from_locs{$from_name};
417 my @arcs;
418 foreach my $from_loc (@$from_locs2) {
419 foreach my $to_loc (@$to_locs2) {
420 my $arc = make_arc($link, $from_loc, $from_name, $to_loc, $to_name, $labs, $encoding);
421 push @arcs, $arc;
422 }
423 }
424 return \@arcs;
425 }
426  
427 sub make_arc {
428 my ($link, $from_loc, $from_name, $to_loc, $to_name, $labs, $encoding) = @_;
429 my $arc = XBRL::JPFR::Arc->new();
430 $arc->to_name($to_name);
431 $arc->from_name($from_name);
432 if (%$labs) {
433 my $to_short = $to_name;
434 my ($to_prefix) = $to_short =~ /(.*)_/;
435 $arc->to_short($to_short);
436 $arc->to_prefix($to_prefix);
437 $arc->text(Encode::encode($encoding, $to_loc->textContent()));
438 $arc->role($to_loc->getAttribute('xlink:role'));
439 $arc->lang($to_loc->getAttribute('xml:lang'));
440 $arc->id($to_loc->getAttribute('id'));
441 }
442 else {
443 my $href = $to_loc->getAttribute('xlink:href');
444 $arc->to_full($href);
445 my ($to_short) = $href =~ m/\#([A-Za-z0-9_-].+)$/;
446 my ($to_prefix) = $to_short =~ /(.*)_/;
447 $arc->to_short($to_short);
448 $arc->to_prefix($to_prefix);
449 }
450 $href = $from_loc->getAttribute('xlink:href');
451 $arc->from_full($href);
452 my ($from_short) = $href =~ m/\#([A-Za-z0-9_-].+)$/;
453 my ($from_prefix) = $from_short =~ /(.*)_/;
454 $arc->from_short($from_short);
455 $arc->from_prefix($from_prefix);
456  
457 my $order = $link->hasAttribute('order') ? $link->getAttribute('order') : 1;
458 my $priority = $link->hasAttribute('priority') ? $link->getAttribute('priority') : 0;
459 my $use = $link->hasAttribute('use') ? $link->getAttribute('use') : 'optional';
460 my $pref = $link->hasAttribute('preferredLabel') ?
461 $link->getAttribute('preferredLabel') : 'http://www.xbrl.org/2003/role/label';
462 $arc->order($order);
463 $arc->arcrole($link->getAttribute('xlink:arcrole'));
464 $arc->closed($link->getAttribute('xbrldt:closed'));
465 $arc->usable($link->getAttribute('xbrldt:usable'));
466 $arc->contextElement($link->getAttribute('xbrldt:contextElement'));
467 $arc->prefLabel($pref);
468 $arc->use($use);
469 $arc->priority($priority);
470 $arc->weight($link->getAttribute('weight'));
471 return $arc;
472 }
473  
474 # DTS rules of discovery:
475 # 3. referenced from a discovered Linkbase document via a <loc> element.
476 # Every taxonomy schema that is referenced by an @xlink:href attribute
477 # on a <loc> element in a discovered linkbase MUST be discovered.
478 sub check_arc_elements {
479 my ($self, $arcs, $labs) = @_;
480 my $elements = $$self{'taxonomy'}{'elements'};
481 foreach my $arc (@$arcs) {
482 my ($from_short, $to_short) = @$arc{'from_short', 'to_short'};
483 if (!exists $$elements{$from_short}) {
484 my $from_full = $$arc{'from_full'};
485 (my $file = $from_full) =~ s/#.*$//;
486 $self->add_schemas([$file]);
487 }
488 if (!exists $$elements{$to_short} && !%$labs) {
489 my $to_full = $$arc{'to_full'};
490 (my $file = $to_full) =~ s/#.*$//;
491 $self->add_schemas([$file]);
492 }
493 }
494 }
495  
496 sub get_trees {
497 my ($self, $type, $uri) = @_;
498 my $trees = $$self{'trees'};
499 $trees = $$trees{$type} if $type;
500 $trees = $$trees{$uri} if $uri;
501 return $trees;
502 }
503  
504 sub get_file {
505 my ($self, $in_file, $dest_dir) = @_;
506  
507 if ($in_file =~ m/^http\:\/\//) {
508 $in_file =~ m/^http\:\/\/[a-zA-Z0-9\/].+\/(.*)$/;
509 my $full_path = File::Spec->catpath(undef, $dest_dir, $1);
510 if (-e $full_path) {
511 return $full_path;
512 }
513  
514 $full_path = File::Spec->catpath(undef, $self->{'schema_dir'}, $1);
515  
516 if (-e $full_path) {
517 return $full_path;
518 }
519 else {
520 my $ua = LWP::UserAgent->new();
521 $ua->agent($agent_string);
522 my $response = $ua->get($in_file);
523 if ($response->is_success) {
524 my $fh;
525 open($fh, ">$full_path") or croak "can't open $full_path because: $! \n";
526 my $cont = $response->content;
527 $cont =~ s/href="(\.\.\/.*?)"/absuri($in_file,$1)/eg;
528 $cont =~ s/href="(\.\/.*?)"/absuri($in_file,$1)/eg;
529 print $fh $cont;
530 close $fh;
531 return $full_path;
532 }
533 else {
534 warn "Unable to retrieve $in_file because: " . $response->status_line . "\n";
535 return undef;
536 }
537 }
538 }
539 else {
540 #process regular file
541 my ($volume, $dir, $filename) = File::Spec->splitpath($in_file);
542  
543 if ($dir && -e $in_file) {
544 return $in_file;
545 }
546  
547 my $test_path = File::Spec->catpath(undef, $$self{'base'}, $filename);
548  
549 if (-e $test_path) {
550 return $test_path;
551 }
552  
553 $test_path = File::Spec->catpath(undef, $$self{'schema_dir'}, $filename);
554 if (-e $test_path) {
555 return $test_path;
556 }
557  
558 # 6779/S0007PA3/ifrs-q3r-E01807-000-2010-12-31-01-2011-02-10.xsd
559 # schemaLocation="../NDK1Q%e3%82%92%e3%82%b3%e3%83%94%e3%81%a3%e3%81%a62Q%e4%bd%9c%e3%82%8b%ef%bc%88IFRS%e3%81%aeXBRL%ef%bc%89/S00073Z6/ifrs-q2r-E01807-000-2010-09-30-01-2010-11-11-entrypoint.xsd
560 if ($filename =~ /entrypoint.xsd/) {
561 my @files = <$$self{'base'}/*-entrypoint.xsd>;
562 return $files[0] if @files;
563 }
564 }
565 }
566  
567 sub absuri {
568 my ($base, $rel) = @_;
569 $base = URI->new($base);
570 my $uri = URI->new($rel);
571 my $abs = $uri->abs($base);
572 return "href=\"$abs\"";
573 }
574  
575 sub make_xpath {
576 #take a file path and return an xpath context
577 my ($self, $in_file, $prefix) = @_;
578  
579 my $xml_doc =XML::LibXML->load_xml( location => $in_file);
580 #print STDERR "IN_FILE=$in_file\n";
581 #print STDERR "IN_FILE=$in_file\n".Dumper($xml_doc);
582 #print STDERR "STRING=". $xml_doc->toString(). "\n";
583 #print STDERR "VALID=". $xml_doc->is_valid(). "\n";
584 #my $root = $xml_doc->documentElement();
585 #print STDERR "ROOT=".Dumper($root);
586 #my @nodes = $root->getChildrenByTagName('*');
587 #print STDERR "NODES=".Dumper(\@nodes);
588 #my $ns = $self->extract_namespaces($xml_doc);
589 #print STDERR "NS=".Dumper($ns);
590  
591 my $xml_xpath = XML::LibXML::XPathContext->new($xml_doc);
592 #print STDERR "XML_XPATH=".Dumper($xml_xpath);
593  
594 my @prefixes = keys %$ns;
595 for (@prefixes) {
596 $xml_xpath->registerNs($_, $ns->{$_});
597 if ($prefix) {
598 if (/-E\d{5}-\d{3}/ || /(tse|tdnet).*-\d{5}$/) {
599 $$prefix = $_;
600 }
601 }
602 }
603  
604 #p3xbrl.com leaves out the link namespace in its schemas
605 $xml_xpath->registerNs('link', 'http://www.xbrl.org/2003/linkbase');
606 #my @nodes = $xml_xpath->findnodes("//*[local-name() = 'import']");
607 #print STDERR "NODES=".Dumper(\@nodes);
608  
609 return $xml_xpath;
610 }
611  
612 sub extract_namespaces {
613 my ($self, $doc) = @_;
614 my %out_hash = ();
615  
616 my $root = $doc->documentElement();
617  
618 my @ns = $root->getNamespaces();
619 for (@ns) {
620 my $localname = $_->getLocalName();
621 if (!$localname) {
622 $out_hash{'default'} = $_->getData();
623 }
624 else {
625 $out_hash{$localname} = $_->getData();
626 }
627 }
628 return \%out_hash;
629 }
630  
631 sub create_trees {
632 my ($self) = @_;
633 return if !$$self{'taxonomy'};
634 foreach my $type ('pre', 'def', 'cal') {
635 my $all_arcs = $$self{'taxonomy'}->$type();
636 next if !$all_arcs;
637 foreach my $roleuri (keys %$all_arcs) {
638 my $arcs = $$all_arcs{$roleuri};
639 next if !$arcs;
640 create_trees_from_arcs($self, $type, $roleuri, $arcs);
641 }
642 }
643 }
644  
645 # 2901/S000DTDB/jpfr-asr-E00471-000-2013-03-31-01-2013-06-27.xbrl
646 # Multi trees(pre,http://info.edinet-fsa.go.jp/jp/fr/gaap/role/NonConsolidatedStatementsOfChangesInNetAssets)
647 # jpfr-cai-an-2013-03-01-presentation.xml
648 # no arc xlink:from="ValuationAndTranslationAdjustmentsSSAbstract" xlink:to="ForeignCurrencyTranslationAdjustmentSSAbstract"
649 # 6891/S000DUXL/jpfr-asr-E01860-000-2013-03-31-01-2013-04-01.xbrl
650 # Multi trees(pre,http://info.edinet-fsa.go.jp/jp/fr/gaap/role/ConsolidatedStatementsOfChangesInNetAssets)
651 # These errors can occur maybe when either NonConsolidated or Consolidated have no data.
652 #
653 sub create_trees_from_arcs {
654 my ($self, $type, $roleuri, $arcs) = @_;
655 my %all;
656 my $elements = $$self{'taxonomy'}{'elements'};
657 my $labels = $$self{'labelhash'};
658 foreach my $arc (@$arcs) {
659 next unless $arc;
660 my ($from_short, $to_short) = @$arc{'from_short', 'to_short'};
661 my ($from_ele, $to_ele) = @$elements{$from_short, $to_short};
662 croak "No element($from_short)".Dumper($arc) if !$from_ele;
663 croak "No element($to_short)".Dumper($arc) if !$to_ele;
664 my $role = $$arc{'arcrole'};
665 my $from_branch = find_branch_by_id_short(\%all, $role, $from_short, $from_ele);
666 my $to_branch = find_branch_by_id_short(\%all, $role, $to_short, $to_ele);
667 $from_branch->connect_to($to_branch, $arc);
668 }
669 my @trees = grep (!$_->from_full(), @{$all{'branches'}});
670 @trees = $$self{'taxonomy'}->discard_prohibiteds(\@trees, $type, $roleuri);
671 warn "Multi trees($type,$roleuri)" if @trees > 1 && $type eq 'pre';
672 warn "No trees($type,$roleuri)" if !@trees;
673 foreach my $tree (@trees) {
674 calc_depth($tree, 0, $type, $roleuri);
675 $tree->splice_undefs();
676 $self->set_tree_labels($roleuri, $tree, $tree);
677 }
678 warn "Trees already exist($type,$roleuri)" if exists $self->{'trees'}{$type}{$roleuri};
679 $$self{'trees'}{$type}{$roleuri} = \@trees;
680 }
681  
682 sub set_tree_labels {
683 my ($self, $roleuri, $tree, $root) = @_;
684 my $id_short = $tree->id_short();
685 my $pref = $tree->prefLabel();
686 my $label = $self->get_label($$self{'lang'}, $id_short, $roleuri, $pref, undef, $root);
687 $tree->label($label);
688 foreach my $to (@{$$tree{'tos'}}) {
689 $self->set_tree_labels($roleuri, $to, $root);
690 }
691 }
692  
693 sub find_branch_by_id_short {
694 my ($all, $role, $short, $ele) = @_;
695 if (exists $$all{$role}{$short}) {
696 return $$all{$role}{$short};
697 }
698 else {
699 my $branch = $$all{$role}{$short} = XBRL::JPFR::Branch->new($ele);
700 push @{$$all{'branches'}}, $branch;
701 return $branch;
702 }
703 }
704  
705 sub calc_depth {
706 my ($tree, $count, $type, $roleuri) = @_;
707 $tree->depth($count);
708 $count++;
709 for (my $i = 0 ; $i < @{$$tree{'tos'}} ; $i++) {
710 my $to = $$tree{'tos'}[$i];
711 my $id_short = $to->id_short();
712 if (defined $to->depth()) {
713 warn "Circular tree. Deleting $id_short from ".$tree->id_short(). "($type,$roleuri).";
714 delete $$tree{'tos'}[$i];
715 next;
716 }
717 calc_depth($to, $count, $type, $roleuri);
718 }
719 }
720  
721 # to decide presentation label in ja, we need XBRL-instance values(XBRL::JPFR::Item).
722 sub get_label {
723 my ($self, $lang, $id_short, $roleuri, $rolelabel, $rolelink, $root) = @_;
724 if ($lang eq 'ja') {
725 return $self->get_label_ja($lang, $id_short, $roleuri, $rolelabel, $rolelink, $root);
726 }
727 else {
728 return $self->get_label_std($lang, $id_short, $rolelabel, $rolelink);
729 }
730 }
731  
732 sub get_label_std {
733 my ($self, $lang, $id_short, $rolelabel, $rolelink) = @_;
734 $rolelabel = 'http://www.xbrl.org/2003/role/label' if !defined $rolelabel;
735 $rolelink = 'http://www.xbrl.org/2003/role/link' if !defined $rolelink;
736 if (!exists $$self{'labelhash'}{$lang}{$id_short}{$rolelink}{$rolelabel}) {
737 warn "No label($lang,$id_short,$rolelink,$rolelabel)";
738 return '';
739 }
740 return $$self{'labelhash'}{$lang}{$id_short}{$rolelink}{$rolelabel};
741 }
742  
743 sub get_label_ja {
744 my ($self, $lang, $id_short, $roleuri, $rolelabel, $rolelink, $root) = @_;
745 $rolelabel = 'http://www.xbrl.org/2003/role/label' if !defined $rolelabel;
746 if ($$self{'std_labels'}) {
747 $rolelink = 'http://www.xbrl.org/2003/role/link';
748 if ($rolelabel =~ /negative/i) {
749 $rolelabel = 'http://www.xbrl.org/2003/role/label';
750 }
751 }
752 else {
753 if (exists $$self{'rolelinks_edinet'}{$roleuri}) {
754 $rolelink = $$self{'rolelinks_edinet'}{$roleuri};
755 }
756 elsif ($rolelink = $self->get_tdnet_rolelink($roleuri, $root)) {
757 }
758 else {
759 $rolelink = 'http://www.xbrl.org/2003/role/link';
760 }
761 }
762 if (exists $$self{'labelhash'}{$lang}{$id_short}{$rolelink}{$rolelabel}) {
763 return $$self{'labelhash'}{$lang}{$id_short}{$rolelink}{$rolelabel};
764 }
765 #warn "Search other label($lang,$id_short,$roleuri,$rolelink,$rolelabel)";
766  
767 if ($$self{'std_labels'}) {
768 if (exists $$self{'rolelinks_edinet'}{$roleuri}) {
769 $rolelink = $$self{'rolelinks_edinet'}{$roleuri};
770 }
771 elsif ($rolelink = $self->get_tdnet_rolelink($roleuri, $root)) {
772 }
773 else {
774 $rolelink = 'http://www.xbrl.org/2003/role/link';
775 }
776 }
777 else {
778 $rolelink = 'http://www.xbrl.org/2003/role/link';
779 if ($rolelabel =~ /negative/i) {
780 $rolelabel = 'http://www.xbrl.org/2003/role/label';
781 }
782 }
783 if (exists $$self{'labelhash'}{$lang}{$id_short}{$rolelink}{$rolelabel}) {
784 return $$self{'labelhash'}{$lang}{$id_short}{$rolelink}{$rolelabel};
785 }
786  
787 #warn "Search other label($lang,$id_short,$roleuri,$rolelink,$rolelabel)";
788 $rolelink = 'http://www.xbrl.org/2003/role/link';
789 my (undef, $base) = File::Spec->splitpath($roleuri);
790 my $pref = (split /\//, $rolelabel)[-1];
791 my @rolelabels = (
792 "http://www.xbrl.org/2003/role/$pref",
793 "$base$pref",
794 "http://www.xbrl.org/2003/role/label",
795 "${base}label",
796 );
797 foreach $rolelabel (@rolelabels) {
798 if (exists $$self{'labelhash'}{$lang}{$id_short}{$rolelink}{$rolelabel}) {
799 return $$self{'labelhash'}{$lang}{$id_short}{$rolelink}{$rolelabel};
800 }
801 }
802  
803 warn "Search existing label($lang,$id_short,$roleuri,$rolelink,$rolelabel)";
804 if (exists $$self{'labelhash'}{$lang}{$id_short}) {
805 my $labels = $$self{'labelhash'}{$lang}{$id_short};
806 foreach my $rolelink (sort {length($a) <=> length($b)} keys %$labels) {
807 foreach my $rolelabel (sort {length($a) <=> length($b)}keys %{$$labels{$rolelink}}) {
808 return $$labels{$rolelink}{$rolelabel};
809 }
810 }
811 }
812  
813 warn "No label($lang,$id_short,$roleuri,$rolelink,$rolelabel)";
814 print STDERR Dumper($$self{'labelhash'}{$lang}{$id_short});
815 return '';
816 }
817  
818 sub get_tdnet_rolelink {
819 my ($self, $roleuri, $root) = @_;
820 return undef if $roleuri !~ /^http:\/\/www.xbrl.tdnet.info\/jp\/br\/tdnet\/role\//;
821 my $rolelink;
822 if ($roleuri =~ /Quarterly|Q1|Q2|Q3/) { # neither Q4 nor Q5 doesnot exist.
823 $rolelink = 'http://www.xbrl.tdnet.info/jp/br/tdnet/role/Quarterly';
824 }
825 if ($self->specific_business_tdnet() && $self->semi_annual_tdnet($roleuri, $root)) {
826 $rolelink = 'http://www.xbrl.tdnet.info/jp/br/tdnet/role/QuarterlyForSpecificBusiness2Q';
827 }
828 return $rolelink;
829 }
830  
831 sub specific_business_tdnet {
832 my ($self) = @_;
833 return 0 if !exists $$self{'itemhash'}{'tse-t-ed_SpecificBusiness'};
834 my ($context) = grep {/Current.*Instant/} keys %{$$self{'itemhash'}{'tse-t-ed_SpecificBusiness'}};
835 my $value = $$self{'itemhash'}{'tse-t-ed_SpecificBusiness'}{$context}{'value'};
836 if ($value =~ /true/i) {
837 return 1;
838 }
839 elsif ($value =~ /false/i) {
840 return 0;
841 }
842 else {
843 croak "No specific business value";
844 }
845 }
846  
847 sub semi_annual_tdnet {
848 my ($self, $roleuri, $root) = @_;
849 if (exists $$self{'itemhash'}{'tse-t-hi_QuarterlyPeriod'}) {
850 my @contexts = keys %{$$self{'itemhash'}{'tse-t-hi_QuarterlyPeriod'}};
851 my ($context) = grep {/Current.*Instant/} @contexts;
852 my $value = $$self{'itemhash'}{'tse-t-hi_QuarterlyPeriod'}{$context}{'value'};
853 if ($value == 2) {
854 return 1;
855 }
856 elsif ($value =~ /[1345]{1}/) {
857 return 0;
858 }
859 else {
860 croak "No quarterly period";
861 }
862 }
863 if ($roleuri =~ /Quarterly/) {
864 my $name = 'ForecastCorrectionOfQuarterlyConsolidatedFinancialResults6MonthsYTDAbstract';
865 my $branch = $root->find_branch_by_name($name);
866 return 1 if $branch;
867 $name = 'ForecastCorrectionOfQuarterlyNonConsolidatedFinancialResults6MonthsYTDAbstract';
868 $branch = $root->find_branch_by_name($name);
869 return $branch ? 1 : 0;
870 }
871 return 0;
872 }
873  
874 BEGIN {
875  
876 my %edinet_2013_03_01_rolelinks = (
877 'ExtendedLinkRoleLabelConsolidatedBS' =>
878 'http://info.edinet-fsa.go.jp/jp/fr/gaap/role/ConsolidatedBalanceSheets',
879 'ExtendedLinkRoleLabelConsolidatedCF' =>
880 'http://info.edinet-fsa.go.jp/jp/fr/gaap/role/ConsolidatedStatementsOfCashFlowsDirect&http://info.edinet-fsa.go.jp/jp/fr/gaap/role/ConsolidatedStatementsOfCashFlowsIndirect',
881 'ExtendedLinkRoleLabelConsolidatedCI' =>
882 'http://info.edinet-fsa.go.jp/jp/fr/gaap/role/ConsolidatedStatementsOfComprehensiveIncome',
883 'ExtendedLinkRoleLabelConsolidatedPL' =>
884 'http://info.edinet-fsa.go.jp/jp/fr/gaap/role/ConsolidatedStatementsOfIncome',
885 'ExtendedLinkRoleLabelConsolidatedSS' =>
886 'http://info.edinet-fsa.go.jp/jp/fr/gaap/role/ConsolidatedStatementsOfChangesInNetAssets',
887 #
888 'ExtendedLinkRoleLabelConsolidatedInterimBS' =>
889 'http://info.edinet-fsa.go.jp/jp/fr/gaap/role/ConsolidatedInterimBalanceSheets',
890 'ExtendedLinkRoleLabelConsolidatedInterimCF' =>
891 'http://info.edinet-fsa.go.jp/jp/fr/gaap/role/ConsolidatedInterimStatementsOfCashFlowsDirect&http://info.edinet-fsa.go.jp/jp/fr/gaap/role/ConsolidatedInterimStatementsOfCashFlowsIndirect',
892 'ExtendedLinkRoleLabelConsolidatedInterimCI' =>
893 'http://info.edinet-fsa.go.jp/jp/fr/gaap/role/ConsolidatedInterimStatementsOfComprehensiveIncome',
894 'ExtendedLinkRoleLabelConsolidatedInterimPL' =>
895 'http://info.edinet-fsa.go.jp/jp/fr/gaap/role/ConsolidatedInterimStatementsOfIncome',
896 'ExtendedLinkRoleLabelConsolidatedInterimSS' =>
897 'http://info.edinet-fsa.go.jp/jp/fr/gaap/role/ConsolidatedInterimStatementsOfChangesInNetAssets',
898 #
899 'ExtendedLinkRoleLabelConsolidatedQuarterlyBS' =>
900 'http://info.edinet-fsa.go.jp/jp/fr/gaap/role/ConsolidatedQuarterlyBalanceSheets',
901 'ExtendedLinkRoleLabelConsolidatedQuarterlyCF' =>
902 'http://info.edinet-fsa.go.jp/jp/fr/gaap/role/ConsolidatedQuarterlyStatementsOfCashFlowsDirect&http://info.edinet-fsa.go.jp/jp/fr/gaap/role/ConsolidatedQuarterlyStatementsOfCashFlowsIndirect',
903 'ExtendedLinkRoleLabelConsolidatedQuarterlyCIQuarter' =>
904 'http://info.edinet-fsa.go.jp/jp/fr/gaap/role/ConsolidatedQuarterlyStatementsOfComprehensiveIncomeQuarter',
905 'ExtendedLinkRoleLabelConsolidatedQuarterlyCIYTD' =>
906 'http://info.edinet-fsa.go.jp/jp/fr/gaap/role/ConsolidatedQuarterlyStatementsOfComprehensiveIncomeYTD',
907 'ExtendedLinkRoleLabelConsolidatedQuarterlyPLQuarter' =>
908 'http://info.edinet-fsa.go.jp/jp/fr/gaap/role/ConsolidatedQuarterlyStatementsOfIncomeQuarter',
909 'ExtendedLinkRoleLabelConsolidatedQuarterlyPLYTD' =>
910 'http://info.edinet-fsa.go.jp/jp/fr/gaap/role/ConsolidatedQuarterlyStatementsOfIncomeYTD',
911 #
912 'ExtendedLinkRoleLabelNonconsolidatedBS' =>
913 'http://info.edinet-fsa.go.jp/jp/fr/gaap/role/NonConsolidatedBalanceSheets',
914 'ExtendedLinkRoleLabelNonconsolidatedCF' =>
915 'http://info.edinet-fsa.go.jp/jp/fr/gaap/role/NonConsolidatedStatementsOfCashFlowsDirect&http://info.edinet-fsa.go.jp/jp/fr/gaap/role/NonConsolidatedStatementsOfCashFlowsIndirect',
916 'ExtendedLinkRoleLabelNonconsolidatedCI' =>
917 'http://info.edinet-fsa.go.jp/jp/fr/gaap/role/NonConsolidatedStatementsOfComprehensiveIncome',
918 'ExtendedLinkRoleLabelNonconsolidatedPL' =>
919 'http://info.edinet-fsa.go.jp/jp/fr/gaap/role/NonConsolidatedStatementsOfIncome',
920 'ExtendedLinkRoleLabelNonconsolidatedSS' =>
921 'http://info.edinet-fsa.go.jp/jp/fr/gaap/role/NonConsolidatedStatementsOfChangesInNetAssets',
922 #
923 'ExtendedLinkRoleLabelNonconsolidatedInterimBS' =>
924 'http://info.edinet-fsa.go.jp/jp/fr/gaap/role/NonConsolidatedInterimBalanceSheets',
925 'ExtendedLinkRoleLabelNonconsolidatedInterimCF' =>
926 'http://info.edinet-fsa.go.jp/jp/fr/gaap/role/NonConsolidatedInterimStatementsOfCashFlowsDirect&http://info.edinet-fsa.go.jp/jp/fr/gaap/role/NonConsolidatedInterimStatementsOfCashFlowsIndirect',
927 'ExtendedLinkRoleLabelNonconsolidatedInterimCI' =>
928 'http://info.edinet-fsa.go.jp/jp/fr/gaap/role/NonConsolidatedInterimStatementsOfComprehensiveIncome',
929 'ExtendedLinkRoleLabelNonconsolidatedInterimPL' =>
930 'http://info.edinet-fsa.go.jp/jp/fr/gaap/role/NonConsolidatedInterimStatementsOfIncome',
931 'ExtendedLinkRoleLabelNonconsolidatedInterimSS' =>
932 'http://info.edinet-fsa.go.jp/jp/fr/gaap/role/NonConsolidatedInterimStatementsOfChangesInNetAssets',
933 #
934 'ExtendedLinkRoleLabelNonconsolidatedQuarterlyBS' =>
935 'http://info.edinet-fsa.go.jp/jp/fr/gaap/role/NonConsolidatedQuarterlyBalanceSheets',
936 'ExtendedLinkRoleLabelNonconsolidatedQuarterlyCF' =>
937 'http://info.edinet-fsa.go.jp/jp/fr/gaap/role/NonConsolidatedQuarterlyStatementsOfCashFlowsDirect&http://info.edinet-fsa.go.jp/jp/fr/gaap/role/NonConsolidatedQuarterlyStatementsOfCashFlowsIndirect',
938 'ExtendedLinkRoleLabelNonconsolidatedQuarterlyCIQuarter' =>
939 'http://info.edinet-fsa.go.jp/jp/fr/gaap/role/NonConsolidatedQuarterlyStatementsOfComprehensiveIncomeQuarter',
940 'ExtendedLinkRoleLabelNonconsolidatedQuarterlyCIYTD' =>
941 'http://info.edinet-fsa.go.jp/jp/fr/gaap/role/NonConsolidatedQuarterlyStatementsOfComprehensiveIncomeYTD',
942 'ExtendedLinkRoleLabelNonconsolidatedQuarterlyPLQuarter' =>
943 'http://info.edinet-fsa.go.jp/jp/fr/gaap/role/NonConsolidatedQuarterlyStatementsOfIncomeQuarter',
944 'ExtendedLinkRoleLabelNonconsolidatedQuarterlyPLYTD' =>
945 'http://info.edinet-fsa.go.jp/jp/fr/gaap/role/NonConsolidatedQuarterlyStatementsOfIncomeYTD',
946 );
947  
948 sub add_rolelink_edinet {
949 my ($self, $localname, $role) = @_;
950 croak "No EDINET rolelink($localname)" if !exists $edinet_2013_03_01_rolelinks{$localname};
951 foreach my $roleuri (split /&/, $edinet_2013_03_01_rolelinks{$localname}) {
952 $$self{'rolelinks_edinet'}{$roleuri} = $role;
953 }
954 }
955  
956 } # BEGIN
957  
958  
959 1;
960  
961 __END__