JPFR.pm untested

filter: Statementstmt 0.0% 0 / 572 Branchbran 0.0% 0 / 216 Conditioncond 0.0% 0 / 34 Subroutinesub 0.0% 0 / 51 Podpod 0.0% 0 / 32 totaltotal 0.0% 0 / 905 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.05';
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 my $ns = $self->extract_namespaces($xml_doc);
581  
582 my $xml_xpath = XML::LibXML::XPathContext->new($xml_doc);
583  
584 my @prefixes = keys %$ns;
585 for (@prefixes) {
586 $xml_xpath->registerNs($_, $ns->{$_});
587 if ($prefix) {
588 if (/-E\d{5}-\d{3}/ || /(tse|tdnet).*-\d{5}$/) {
589 $$prefix = $_;
590 }
591 }
592 }
593  
594 #p3xbrl.com leaves out the link namespace in its schemas
595 $xml_xpath->registerNs('link', 'http://www.xbrl.org/2003/linkbase');
596  
597 return $xml_xpath;
598 }
599  
600 sub extract_namespaces {
601 my ($self, $doc) = @_;
602 my %out_hash = ();
603  
604 my $root = $doc->documentElement();
605  
606 my @ns = $root->getNamespaces();
607 for (@ns) {
608 my $localname = $_->getLocalName();
609 if (!$localname) {
610 $out_hash{'default'} = $_->getData();
611 }
612 else {
613 $out_hash{$localname} = $_->getData();
614 }
615 }
616 return \%out_hash;
617 }
618  
619 sub create_trees {
620 my ($self) = @_;
621 return if !$$self{'taxonomy'};
622 foreach my $type ('pre', 'def', 'cal') {
623 my $all_arcs = $$self{'taxonomy'}->$type();
624 next if !$all_arcs;
625 foreach my $roleuri (keys %$all_arcs) {
626 my $arcs = $$all_arcs{$roleuri};
627 next if !$arcs;
628 create_trees_from_arcs($self, $type, $roleuri, $arcs);
629 }
630 }
631 }
632  
633 # 2901/S000DTDB/jpfr-asr-E00471-000-2013-03-31-01-2013-06-27.xbrl
634 # Multi trees(pre,http://info.edinet-fsa.go.jp/jp/fr/gaap/role/NonConsolidatedStatementsOfChangesInNetAssets)
635 # jpfr-cai-an-2013-03-01-presentation.xml
636 # no arc xlink:from="ValuationAndTranslationAdjustmentsSSAbstract" xlink:to="ForeignCurrencyTranslationAdjustmentSSAbstract"
637 # 6891/S000DUXL/jpfr-asr-E01860-000-2013-03-31-01-2013-04-01.xbrl
638 # Multi trees(pre,http://info.edinet-fsa.go.jp/jp/fr/gaap/role/ConsolidatedStatementsOfChangesInNetAssets)
639 # These errors can occur maybe when either NonConsolidated or Consolidated have no data.
640 #
641 sub create_trees_from_arcs {
642 my ($self, $type, $roleuri, $arcs) = @_;
643 my %all;
644 my $elements = $$self{'taxonomy'}{'elements'};
645 my $labels = $$self{'labelhash'};
646 foreach my $arc (@$arcs) {
647 next unless $arc;
648 my ($from_short, $to_short) = @$arc{'from_short', 'to_short'};
649 my ($from_ele, $to_ele) = @$elements{$from_short, $to_short};
650 croak "No element($from_short)".Dumper($arc) if !$from_ele;
651 croak "No element($to_short)".Dumper($arc) if !$to_ele;
652 my $role = $$arc{'arcrole'};
653 my $from_branch = find_branch_by_id_short(\%all, $role, $from_short, $from_ele);
654 my $to_branch = find_branch_by_id_short(\%all, $role, $to_short, $to_ele);
655 $from_branch->connect_to($to_branch, $arc);
656 }
657 my @trees = grep (!$_->from_full(), @{$all{'branches'}});
658 @trees = $$self{'taxonomy'}->discard_prohibiteds(\@trees, $type, $roleuri);
659 warn "Multi trees($type,$roleuri)" if @trees > 1 && $type eq 'pre';
660 warn "No trees($type,$roleuri)" if !@trees;
661 foreach my $tree (@trees) {
662 calc_depth($tree, 0, $type, $roleuri);
663 $tree->splice_undefs();
664 $self->set_tree_labels($roleuri, $tree, $tree);
665 }
666 warn "Trees already exist($type,$roleuri)" if exists $self->{'trees'}{$type}{$roleuri};
667 $$self{'trees'}{$type}{$roleuri} = \@trees;
668 }
669  
670 sub set_tree_labels {
671 my ($self, $roleuri, $tree, $root) = @_;
672 my $id_short = $tree->id_short();
673 my $pref = $tree->prefLabel();
674 my $label = $self->get_label($$self{'lang'}, $id_short, $roleuri, $pref, undef, $root);
675 $tree->label($label);
676 foreach my $to (@{$$tree{'tos'}}) {
677 $self->set_tree_labels($roleuri, $to, $root);
678 }
679 }
680  
681 sub find_branch_by_id_short {
682 my ($all, $role, $short, $ele) = @_;
683 if (exists $$all{$role}{$short}) {
684 return $$all{$role}{$short};
685 }
686 else {
687 my $branch = $$all{$role}{$short} = XBRL::JPFR::Branch->new($ele);
688 push @{$$all{'branches'}}, $branch;
689 return $branch;
690 }
691 }
692  
693 sub calc_depth {
694 my ($tree, $count, $type, $roleuri) = @_;
695 $tree->depth($count);
696 $count++;
697 for (my $i = 0 ; $i < @{$$tree{'tos'}} ; $i++) {
698 my $to = $$tree{'tos'}[$i];
699 my $id_short = $to->id_short();
700 if (defined $to->depth()) {
701 warn "Circular tree. Deleting $id_short from ".$tree->id_short(). "($type,$roleuri).";
702 delete $$tree{'tos'}[$i];
703 next;
704 }
705 calc_depth($to, $count, $type, $roleuri);
706 }
707 }
708  
709 # to decide presentation label in ja, we need XBRL-instance values(XBRL::JPFR::Item).
710 sub get_label {
711 my ($self, $lang, $id_short, $roleuri, $rolelabel, $rolelink, $root) = @_;
712 if ($lang eq 'ja') {
713 return $self->get_label_ja($lang, $id_short, $roleuri, $rolelabel, $rolelink, $root);
714 }
715 else {
716 return $self->get_label_std($lang, $id_short, $rolelabel, $rolelink);
717 }
718 }
719  
720 sub get_label_std {
721 my ($self, $lang, $id_short, $rolelabel, $rolelink) = @_;
722 $rolelabel = 'http://www.xbrl.org/2003/role/label' if !defined $rolelabel;
723 $rolelink = 'http://www.xbrl.org/2003/role/link' if !defined $rolelink;
724 if (!exists $$self{'labelhash'}{$lang}{$id_short}{$rolelink}{$rolelabel}) {
725 warn "No label($lang,$id_short,$rolelink,$rolelabel)";
726 return '';
727 }
728 return $$self{'labelhash'}{$lang}{$id_short}{$rolelink}{$rolelabel};
729 }
730  
731 sub get_label_ja {
732 my ($self, $lang, $id_short, $roleuri, $rolelabel, $rolelink, $root) = @_;
733 $rolelabel = 'http://www.xbrl.org/2003/role/label' if !defined $rolelabel;
734 if ($$self{'std_labels'}) {
735 $rolelink = 'http://www.xbrl.org/2003/role/link';
736 if ($rolelabel =~ /negative/i) {
737 $rolelabel = 'http://www.xbrl.org/2003/role/label';
738 }
739 }
740 else {
741 if (exists $$self{'rolelinks_edinet'}{$roleuri}) {
742 $rolelink = $$self{'rolelinks_edinet'}{$roleuri};
743 }
744 elsif ($rolelink = $self->get_tdnet_rolelink($roleuri, $root)) {
745 }
746 else {
747 $rolelink = 'http://www.xbrl.org/2003/role/link';
748 }
749 }
750 if (exists $$self{'labelhash'}{$lang}{$id_short}{$rolelink}{$rolelabel}) {
751 return $$self{'labelhash'}{$lang}{$id_short}{$rolelink}{$rolelabel};
752 }
753 #warn "Search other label($lang,$id_short,$roleuri,$rolelink,$rolelabel)";
754  
755 if ($$self{'std_labels'}) {
756 if (exists $$self{'rolelinks_edinet'}{$roleuri}) {
757 $rolelink = $$self{'rolelinks_edinet'}{$roleuri};
758 }
759 elsif ($rolelink = $self->get_tdnet_rolelink($roleuri, $root)) {
760 }
761 else {
762 $rolelink = 'http://www.xbrl.org/2003/role/link';
763 }
764 }
765 else {
766 $rolelink = 'http://www.xbrl.org/2003/role/link';
767 if ($rolelabel =~ /negative/i) {
768 $rolelabel = 'http://www.xbrl.org/2003/role/label';
769 }
770 }
771 if (exists $$self{'labelhash'}{$lang}{$id_short}{$rolelink}{$rolelabel}) {
772 return $$self{'labelhash'}{$lang}{$id_short}{$rolelink}{$rolelabel};
773 }
774  
775 #warn "Search other label($lang,$id_short,$roleuri,$rolelink,$rolelabel)";
776 $rolelink = 'http://www.xbrl.org/2003/role/link';
777 my (undef, $base) = File::Spec->splitpath($roleuri);
778 my $pref = (split /\//, $rolelabel)[-1];
779 my @rolelabels = (
780 "http://www.xbrl.org/2003/role/$pref",
781 "$base$pref",
782 "http://www.xbrl.org/2003/role/label",
783 "${base}label",
784 );
785 foreach $rolelabel (@rolelabels) {
786 if (exists $$self{'labelhash'}{$lang}{$id_short}{$rolelink}{$rolelabel}) {
787 return $$self{'labelhash'}{$lang}{$id_short}{$rolelink}{$rolelabel};
788 }
789 }
790  
791 warn "Search existing label($lang,$id_short,$roleuri,$rolelink,$rolelabel)";
792 if (exists $$self{'labelhash'}{$lang}{$id_short}) {
793 my $labels = $$self{'labelhash'}{$lang}{$id_short};
794 foreach my $rolelink (sort {length($a) <=> length($b)} keys %$labels) {
795 foreach my $rolelabel (sort {length($a) <=> length($b)}keys %{$$labels{$rolelink}}) {
796 return $$labels{$rolelink}{$rolelabel};
797 }
798 }
799 }
800  
801 warn "No label($lang,$id_short,$roleuri,$rolelink,$rolelabel)";
802 print STDERR Dumper($$self{'labelhash'}{$lang}{$id_short});
803 return '';
804 }
805  
806 sub get_tdnet_rolelink {
807 my ($self, $roleuri, $root) = @_;
808 return undef if $roleuri !~ /^http:\/\/www.xbrl.tdnet.info\/jp\/br\/tdnet\/role\//;
809 my $rolelink;
810 if ($roleuri =~ /Quarterly|Q1|Q2|Q3/) { # neither Q4 nor Q5 doesnot exist.
811 $rolelink = 'http://www.xbrl.tdnet.info/jp/br/tdnet/role/Quarterly';
812 }
813 if ($self->specific_business_tdnet() && $self->semi_annual_tdnet($roleuri, $root)) {
814 $rolelink = 'http://www.xbrl.tdnet.info/jp/br/tdnet/role/QuarterlyForSpecificBusiness2Q';
815 }
816 return $rolelink;
817 }
818  
819 sub specific_business_tdnet {
820 my ($self) = @_;
821 return 0 if !exists $$self{'itemhash'}{'tse-t-ed_SpecificBusiness'};
822 my ($context) = grep {/Current.*Instant/} keys %{$$self{'itemhash'}{'tse-t-ed_SpecificBusiness'}};
823 my $value = $$self{'itemhash'}{'tse-t-ed_SpecificBusiness'}{$context}{'value'};
824 if ($value =~ /true/i) {
825 return 1;
826 }
827 elsif ($value =~ /false/i) {
828 return 0;
829 }
830 else {
831 croak "No specific business value";
832 }
833 }
834  
835 sub semi_annual_tdnet {
836 my ($self, $roleuri, $root) = @_;
837 if (exists $$self{'itemhash'}{'tse-t-hi_QuarterlyPeriod'}) {
838 my @contexts = keys %{$$self{'itemhash'}{'tse-t-hi_QuarterlyPeriod'}};
839 my ($context) = grep {/Current.*Instant/} @contexts;
840 my $value = $$self{'itemhash'}{'tse-t-hi_QuarterlyPeriod'}{$context}{'value'};
841 if ($value == 2) {
842 return 1;
843 }
844 elsif ($value =~ /[1345]{1}/) {
845 return 0;
846 }
847 else {
848 croak "No quarterly period";
849 }
850 }
851 if ($roleuri =~ /Quarterly/) {
852 my $name = 'ForecastCorrectionOfQuarterlyConsolidatedFinancialResults6MonthsYTDAbstract';
853 my $branch = $root->find_branch_by_name($name);
854 return 1 if $branch;
855 $name = 'ForecastCorrectionOfQuarterlyNonConsolidatedFinancialResults6MonthsYTDAbstract';
856 $branch = $root->find_branch_by_name($name);
857 return $branch ? 1 : 0;
858 }
859 return 0;
860 }
861  
862 BEGIN {
863  
864 my %edinet_2013_03_01_rolelinks = (
865 'ExtendedLinkRoleLabelConsolidatedBS' =>
866 'http://info.edinet-fsa.go.jp/jp/fr/gaap/role/ConsolidatedBalanceSheets',
867 'ExtendedLinkRoleLabelConsolidatedCF' =>
868 'http://info.edinet-fsa.go.jp/jp/fr/gaap/role/ConsolidatedStatementsOfCashFlowsDirect&http://info.edinet-fsa.go.jp/jp/fr/gaap/role/ConsolidatedStatementsOfCashFlowsIndirect',
869 'ExtendedLinkRoleLabelConsolidatedCI' =>
870 'http://info.edinet-fsa.go.jp/jp/fr/gaap/role/ConsolidatedStatementsOfComprehensiveIncome',
871 'ExtendedLinkRoleLabelConsolidatedPL' =>
872 'http://info.edinet-fsa.go.jp/jp/fr/gaap/role/ConsolidatedStatementsOfIncome',
873 'ExtendedLinkRoleLabelConsolidatedSS' =>
874 'http://info.edinet-fsa.go.jp/jp/fr/gaap/role/ConsolidatedStatementsOfChangesInNetAssets',
875 #
876 'ExtendedLinkRoleLabelConsolidatedInterimBS' =>
877 'http://info.edinet-fsa.go.jp/jp/fr/gaap/role/ConsolidatedInterimBalanceSheets',
878 'ExtendedLinkRoleLabelConsolidatedInterimCF' =>
879 'http://info.edinet-fsa.go.jp/jp/fr/gaap/role/ConsolidatedInterimStatementsOfCashFlowsDirect&http://info.edinet-fsa.go.jp/jp/fr/gaap/role/ConsolidatedInterimStatementsOfCashFlowsIndirect',
880 'ExtendedLinkRoleLabelConsolidatedInterimCI' =>
881 'http://info.edinet-fsa.go.jp/jp/fr/gaap/role/ConsolidatedInterimStatementsOfComprehensiveIncome',
882 'ExtendedLinkRoleLabelConsolidatedInterimPL' =>
883 'http://info.edinet-fsa.go.jp/jp/fr/gaap/role/ConsolidatedInterimStatementsOfIncome',
884 'ExtendedLinkRoleLabelConsolidatedInterimSS' =>
885 'http://info.edinet-fsa.go.jp/jp/fr/gaap/role/ConsolidatedInterimStatementsOfChangesInNetAssets',
886 #
887 'ExtendedLinkRoleLabelConsolidatedQuarterlyBS' =>
888 'http://info.edinet-fsa.go.jp/jp/fr/gaap/role/ConsolidatedQuarterlyBalanceSheets',
889 'ExtendedLinkRoleLabelConsolidatedQuarterlyCF' =>
890 'http://info.edinet-fsa.go.jp/jp/fr/gaap/role/ConsolidatedQuarterlyStatementsOfCashFlowsDirect&http://info.edinet-fsa.go.jp/jp/fr/gaap/role/ConsolidatedQuarterlyStatementsOfCashFlowsIndirect',
891 'ExtendedLinkRoleLabelConsolidatedQuarterlyCIQuarter' =>
892 'http://info.edinet-fsa.go.jp/jp/fr/gaap/role/ConsolidatedQuarterlyStatementsOfComprehensiveIncomeQuarter',
893 'ExtendedLinkRoleLabelConsolidatedQuarterlyCIYTD' =>
894 'http://info.edinet-fsa.go.jp/jp/fr/gaap/role/ConsolidatedQuarterlyStatementsOfComprehensiveIncomeYTD',
895 'ExtendedLinkRoleLabelConsolidatedQuarterlyPLQuarter' =>
896 'http://info.edinet-fsa.go.jp/jp/fr/gaap/role/ConsolidatedQuarterlyStatementsOfIncomeQuarter',
897 'ExtendedLinkRoleLabelConsolidatedQuarterlyPLYTD' =>
898 'http://info.edinet-fsa.go.jp/jp/fr/gaap/role/ConsolidatedQuarterlyStatementsOfIncomeYTD',
899 #
900 'ExtendedLinkRoleLabelNonconsolidatedBS' =>
901 'http://info.edinet-fsa.go.jp/jp/fr/gaap/role/NonConsolidatedBalanceSheets',
902 'ExtendedLinkRoleLabelNonconsolidatedCF' =>
903 'http://info.edinet-fsa.go.jp/jp/fr/gaap/role/NonConsolidatedStatementsOfCashFlowsDirect&http://info.edinet-fsa.go.jp/jp/fr/gaap/role/NonConsolidatedStatementsOfCashFlowsIndirect',
904 'ExtendedLinkRoleLabelNonconsolidatedCI' =>
905 'http://info.edinet-fsa.go.jp/jp/fr/gaap/role/NonConsolidatedStatementsOfComprehensiveIncome',
906 'ExtendedLinkRoleLabelNonconsolidatedPL' =>
907 'http://info.edinet-fsa.go.jp/jp/fr/gaap/role/NonConsolidatedStatementsOfIncome',
908 'ExtendedLinkRoleLabelNonconsolidatedSS' =>
909 'http://info.edinet-fsa.go.jp/jp/fr/gaap/role/NonConsolidatedStatementsOfChangesInNetAssets',
910 #
911 'ExtendedLinkRoleLabelNonconsolidatedInterimBS' =>
912 'http://info.edinet-fsa.go.jp/jp/fr/gaap/role/NonConsolidatedInterimBalanceSheets',
913 'ExtendedLinkRoleLabelNonconsolidatedInterimCF' =>
914 'http://info.edinet-fsa.go.jp/jp/fr/gaap/role/NonConsolidatedInterimStatementsOfCashFlowsDirect&http://info.edinet-fsa.go.jp/jp/fr/gaap/role/NonConsolidatedInterimStatementsOfCashFlowsIndirect',
915 'ExtendedLinkRoleLabelNonconsolidatedInterimCI' =>
916 'http://info.edinet-fsa.go.jp/jp/fr/gaap/role/NonConsolidatedInterimStatementsOfComprehensiveIncome',
917 'ExtendedLinkRoleLabelNonconsolidatedInterimPL' =>
918 'http://info.edinet-fsa.go.jp/jp/fr/gaap/role/NonConsolidatedInterimStatementsOfIncome',
919 'ExtendedLinkRoleLabelNonconsolidatedInterimSS' =>
920 'http://info.edinet-fsa.go.jp/jp/fr/gaap/role/NonConsolidatedInterimStatementsOfChangesInNetAssets',
921 #
922 'ExtendedLinkRoleLabelNonconsolidatedQuarterlyBS' =>
923 'http://info.edinet-fsa.go.jp/jp/fr/gaap/role/NonConsolidatedQuarterlyBalanceSheets',
924 'ExtendedLinkRoleLabelNonconsolidatedQuarterlyCF' =>
925 'http://info.edinet-fsa.go.jp/jp/fr/gaap/role/NonConsolidatedQuarterlyStatementsOfCashFlowsDirect&http://info.edinet-fsa.go.jp/jp/fr/gaap/role/NonConsolidatedQuarterlyStatementsOfCashFlowsIndirect',
926 'ExtendedLinkRoleLabelNonconsolidatedQuarterlyCIQuarter' =>
927 'http://info.edinet-fsa.go.jp/jp/fr/gaap/role/NonConsolidatedQuarterlyStatementsOfComprehensiveIncomeQuarter',
928 'ExtendedLinkRoleLabelNonconsolidatedQuarterlyCIYTD' =>
929 'http://info.edinet-fsa.go.jp/jp/fr/gaap/role/NonConsolidatedQuarterlyStatementsOfComprehensiveIncomeYTD',
930 'ExtendedLinkRoleLabelNonconsolidatedQuarterlyPLQuarter' =>
931 'http://info.edinet-fsa.go.jp/jp/fr/gaap/role/NonConsolidatedQuarterlyStatementsOfIncomeQuarter',
932 'ExtendedLinkRoleLabelNonconsolidatedQuarterlyPLYTD' =>
933 'http://info.edinet-fsa.go.jp/jp/fr/gaap/role/NonConsolidatedQuarterlyStatementsOfIncomeYTD',
934 );
935  
936 sub add_rolelink_edinet {
937 my ($self, $localname, $role) = @_;
938 croak "No EDINET rolelink($localname)" if !exists $edinet_2013_03_01_rolelinks{$localname};
939 foreach my $roleuri (split /&/, $edinet_2013_03_01_rolelinks{$localname}) {
940 $$self{'rolelinks_edinet'}{$roleuri} = $role;
941 }
942 }
943  
944 } # BEGIN
945  
946  
947 1;
948  
949 __END__