merge PathElement::* into Path::Node
[id3fs.git] / lib / ID3FS / Path.pm
1 package ID3FS::Path;
2
3 use strict;
4 use warnings;
5 use ID3FS::Path::Node;
6
7 our ($STATE_INVALID, $STATE_ROOT, $STATE_TAG, $STATE_TAGVAL,
8      $STATE_BOOLEAN, $STATE_ALBUMS, $STATE_TRACKLIST,
9      $STATE_FILE, $STATE_ALL)=(0..8);
10
11 our %priorities=( "OR" => 0, "AND" => 1, "NOT" => 2 );
12
13 our $PATH_ALLTRACKS="TRACKS";
14 our $PATH_NOARTIST="NOARTIST";
15 our $PATH_NOALBUM="NOALBUM";
16
17 sub new
18 {
19     my $proto=shift;
20     my $class=ref($proto) || $proto;
21     my $self={};
22     bless($self,$class);
23
24     $self->{elements}=[];
25     $self->{db}=shift;
26     $self->{path}=shift;
27     $self->{verbose}=shift;
28     $self->{maxtagdepth}=shift;
29     $self->{curtagdepth}=0;
30     $self->{path} =~ s/\/\//\//g; # drop doubled slashes
31
32     $self->parse();
33 #    print "STATE: ", $self->state(), "\n";
34     return $self;
35 }
36
37 sub isdir
38 {
39     my($self)=@_;
40     if(($self->state() == $STATE_FILE) ||
41        ($self->state() == $STATE_INVALID))
42     {
43         return 0;
44     }
45     return 1;
46 }
47
48 sub isfile
49 {
50     my($self)=@_;
51     return($self->state() == $STATE_FILE);
52 }
53
54 sub isvalid
55 {
56     my($self)=@_;
57     return($self->state() != $STATE_INVALID);
58 }
59
60 sub dest
61 {
62     my($self, $mountpoint)=@_;
63     if($self->state() == $STATE_FILE)
64     {
65         return $self->filename($mountpoint);
66     }
67     return "ERROR"; #should never happen?
68 }
69
70 sub dirents
71 {
72     my($self)=@_;
73     my @dents=();
74     my @fents=();
75     my $state=$self->state();
76 #    print "DIRENTS: STATE: $state\n";
77 #    print "DIRENTS: FILE: $self->{path}\n";
78     if($state==$STATE_ALL)
79     {
80         @dents=($PATH_ALLTRACKS, $PATH_NOARTIST, $self->artists());
81     }
82     elsif($state==$STATE_TAG || $state==$STATE_TAGVAL)
83     {
84         if($state==$STATE_TAG && $self->at("tag") &&
85            $self->{db}->tag_has_values($self->tail()->id()))
86         {
87             @dents=$self->tags();
88         }
89         else
90         {
91             if($self->{maxtagdepth} && ($self->{curtagdepth} < $self->{maxtagdepth}))
92             {
93                 @dents=qw(AND OR);
94             }
95             push(@dents, $self->filter($PATH_ALLTRACKS, $PATH_NOARTIST));
96             push(@dents, $self->artists());
97         }
98     }
99     elsif($state==$STATE_BOOLEAN)
100     {
101         my $parent=$self->tail();
102         unless($self->is("boolean", $parent) &&
103                $parent->{name} eq "NOT")
104         {
105             @dents=("NOT");
106         }
107         push(@dents,$self->tags());
108     }
109     elsif($state==$STATE_ROOT)
110     {
111         @dents=(qw(ALL NOT), $self->tags());
112     }
113     elsif($state==$STATE_ALBUMS)
114     {
115         @dents=($self->filter($PATH_ALLTRACKS, $PATH_NOALBUM), $self->albums());
116     }
117     elsif($state==$STATE_TRACKLIST)
118     {
119         @fents=$self->tracks();
120     }
121     else
122     {
123         print "DIRENTS: UNHANDLED STATE: $state\n";
124     }
125     return(\@dents, \@fents);
126 }
127
128 sub parse
129 {
130     my($self)=@_;
131     @{$self->{components}}=split(/\//, $self->{path});
132     shift @{$self->{components}}; # drop empty field before leading /
133 #    print "PATH: $self->{path}\n";
134     $self->state($STATE_ROOT);
135     return if($self->{path} eq "/");
136     my @parts=@{$self->{components}};
137     my($tag, $tagval);
138     $self->{elements}=[];
139     $self->{bare_not}=0;
140     $self->{in_all}=0;
141     my $root_not=0;
142     my $tags_seen=0;
143     while(defined(my $name=shift @parts))
144     {
145 #       print "NAME: $name\n";
146         my $state=$self->state();
147         if($state==$STATE_INVALID)
148         {
149 #           print "SM: INVALID: $name\n";
150             return;
151         }
152         elsif($state==$STATE_ROOT)
153         {
154 #           print "SM: ROOT: $name\n";
155             if($name eq "ALL")
156             {
157                 $self->{in_all}=1;
158                 $self->state($STATE_ALL);
159             }
160             elsif($name eq "NOT")
161             {
162                 $root_not=1;
163                 push(@{$self->{elements}}, ID3FS::Path::Node->new($self->{db}, "boolean", $name));
164                 $self->state($STATE_BOOLEAN);
165             }
166             else
167             {
168                 $tag=ID3FS::Path::Node->new($self->{db},"tag", $name);
169                 if($tag)
170                 {
171                     push(@{$self->{elements}}, $tag);
172                     $tags_seen++;
173                     $self->state($STATE_TAG);
174                 }
175                 else
176                 {
177                     $self->state($STATE_INVALID);
178                 }
179             }
180         }
181         elsif($state==$STATE_TAG || $state==$STATE_TAGVAL)
182         {
183             my $tag=$self->tail();
184 #           print "SM: TAG/TAGVAL($state): $name\n";
185             if($state==$STATE_TAG && $self->is("tag", $tag) &&
186                $self->{db}->tag_has_values($tag->id()))
187             {
188 #               print "Parsing: parent: $tag->id()\n";
189                 my $tagval=ID3FS::Path::Node->new($self->{db}, "tag", $name, $tag->id());
190                 if(defined($tagval))
191                 {
192                     $self->state($STATE_TAGVAL);
193                     # stay in tag state
194                     push(@{$self->{elements}}, $tagval);
195                 }
196                 else
197                 {
198                     $self->state($STATE_INVALID);
199                 }
200             }
201             elsif($name eq $PATH_ALLTRACKS)
202             {
203                 $self->state($STATE_TRACKLIST);
204             }
205             elsif($name eq $PATH_NOARTIST)
206             {
207                 $self->state($STATE_TRACKLIST);
208             }
209             elsif($name eq "AND")
210             {
211                 $self->state($STATE_BOOLEAN);
212                 push(@{$self->{elements}}, ID3FS::Path::Node->new($self->{db}, "boolean", $name));
213             }
214             elsif($name eq "OR")
215             {
216                 $self->state($STATE_BOOLEAN);
217                 push(@{$self->{elements}}, ID3FS::Path::Node->new($self->{db}, "boolean", $name));
218             }
219             else
220             {
221                 my $artist=ID3FS::Path::Node->new($self->{db}, "artist", $name);
222                 if($artist)
223                 {
224                     push(@{$self->{elements}}, $artist);
225                     $self->state($STATE_ALBUMS);
226                 }
227                 else
228                 {
229                     $self->state($STATE_INVALID);
230                 }
231             }
232         }
233         elsif($state==$STATE_BOOLEAN)
234         {
235 #           print "SM: BOOLEAN: $name\n";
236             my $parent=$self->tail();
237             my $allownot=1;
238             if($self->is("boolean", $parent) &&
239                $parent->{name} eq "NOT")
240             {
241                 $allownot=0;
242             }
243             if($allownot && $name eq "NOT")
244             {
245                 $self->state($STATE_BOOLEAN);
246                 push(@{$self->{elements}}, ID3FS::Path::Node->new($self->{db}, "boolean", $name));
247             }
248             else
249             {
250                 my $tag=ID3FS::Path::Node->new($self->{db}, "tag", $name);
251                 if($tag)
252                 {
253                     push(@{$self->{elements}}, $tag);
254                     $tags_seen++;
255                     $self->state($STATE_TAG);
256                 }
257                 else
258                 {
259                     $self->state($STATE_INVALID);
260                 }
261             }
262         }
263         elsif($state==$STATE_ALBUMS)
264         {
265 #           print "SM: ALBUM: $name\n";
266             if($name eq $PATH_ALLTRACKS)
267             {
268                 $self->state($STATE_TRACKLIST);
269             }
270             elsif($name eq $PATH_NOALBUM)
271             {
272                 $self->state($STATE_TRACKLIST);
273             }
274             else
275             {
276                 my $album=ID3FS::Path::Node->new($self->{db}, "album", $name);
277                 if($album)
278                 {
279                     push(@{$self->{elements}}, $album);
280                     $self->state($STATE_TRACKLIST);
281                 }
282                 else
283                 {
284                     $self->state($STATE_INVALID);
285                 }
286             }
287         }
288         elsif($state==$STATE_TRACKLIST)
289         {
290 #           print "SM: TRACKLIST: $name\n";
291             my $track=ID3FS::Path::Node->new($self->{db}, "file", $name);
292             if($track)
293             {
294                 push(@{$self->{elements}}, $track);
295                 $self->state($STATE_FILE);
296             }
297             else
298             {
299                 $self->state($STATE_INVALID);
300             }
301         }
302         elsif($state==$STATE_FILE)
303         {
304 #           print "SM: FILE: $name\n";
305             # Can't have anything after a filename
306             $self->state($STATE_INVALID);
307         }
308         elsif($state==$STATE_ALL)
309         {
310             if($name eq $PATH_ALLTRACKS)
311             {
312                 $self->state($STATE_TRACKLIST);
313             }
314             elsif($name eq $PATH_NOARTIST)
315             {
316                 $self->state($STATE_TRACKLIST);
317             }
318             else
319             {
320                 my $artist=ID3FS::Path::Node->new($self->{db}, "artist", $name);
321                 if($artist)
322                 {
323                     push(@{$self->{elements}}, $artist);
324                     $self->state($STATE_ALBUMS);
325                 }
326                 else
327                 {
328                     $self->state($STATE_INVALID);
329                 }
330             }
331         }
332         else
333         {
334             print "SM: ERROR: UNKNOWN STATE: $self->{state}\n";
335             $self->state($STATE_INVALID);
336         }
337     }
338
339     if($root_not && ($tags_seen < 2))
340     {
341         $self->{bare_not}=1;
342     }
343
344     # remove trailing boolean
345     my @elements=@{$self->{elements}};
346     while(@elements && $self->is("boolean", $elements[$#elements]))
347     {
348         pop @elements;
349     }
350     # sort elements by precedence
351     @elements=$self->sort_elements(@elements);
352     $self->{tagtree}=$self->elements_to_tree(\@elements);
353     if($self->{tagtree})
354     {
355         my ($conditions, @joins)=$self->{tagtree}->to_sql();
356 #       print "CONDITIONS(", scalar(@joins), "): ", $conditions, "\n";
357 #       print "TREE: ",  $self->{tagtree}->print(), "\n";
358 #       print("SQL CONDITION(", scalar(@{$self->{joins}}), "): ",
359 #             $self->{sqlconditions}, "\n");
360 #       use Data::Dumper;
361 #       print Dumper $self->{tagtree};
362     }
363 }
364
365 sub state
366 {
367     my($self, $newstate)=@_;
368     if(defined($newstate))
369     {
370         $self->{state}=$newstate;
371         $self->{curtagdepth}++ if($newstate == $STATE_TAG);
372     }
373     return $self->{state};
374 }
375
376 sub elements_to_tree
377 {
378     my($self, $elements)=@_;
379     return undef unless(@$elements);
380     my ($left, $right, $op)=(undef, undef, undef);
381     my $thing=pop @$elements;
382     if($self->is("boolean", $thing))
383     {
384         $right=$self->elements_to_tree($elements);
385         if($thing->{name} ne "NOT")
386         {
387             $left=$self->elements_to_tree($elements);
388         }
389         $thing->left($left);
390         $thing->right($right);
391     }
392     return $thing;
393 }
394
395 # Dijkstra's shunting-yard algorithm
396 sub sort_elements
397 {
398     my ($self, @input)=@_;
399     my @opstack=();
400     my @output=();
401 #    print "INPUT: ", join(', ', map { $_->{name}; } @input), "\n";
402     while(my $thing = shift @input)
403     {
404         if($self->is("tag", $thing))
405         {
406             # Handle tag values by dropping parent
407             if(@input && $self->is("tag", $input[0]))
408             {
409                 $thing=shift @input;
410             }
411             push(@output, $thing);
412         }
413         elsif($self->is("boolean", $thing))
414         {
415             # bool
416             while(@opstack &&
417                   ($priorities{$thing->{name}} <= $priorities{$opstack[$#opstack]->{name}}))
418             {
419                 push(@output, pop(@opstack));
420             }
421             push(@opstack, $thing);
422         }
423     }
424     while(@opstack)
425     {
426         push(@output, pop(@opstack));
427     }
428 #    print "STACK: ", join(', ', map { $_->{name}; } @output), "\n";
429     return @output;
430 }
431
432 sub used_tags
433 {
434     my($self)=@_;
435     return() unless(defined($self->{tagtree}));
436     return($self->{tagtree}->used_tags());
437 }
438
439 sub expecting_values
440 {
441     my($self)=@_;
442     my $tail=$self->tail();
443     if($self->is("tag", $tail))
444     {
445         return($self->{db}->tag_has_values($tail->id()));
446     }
447 }
448
449 sub trailing_tag_id
450 {
451     my($self)=@_;
452     my $tail=$self->tail();
453     if($self->is("tag", $tail))
454     {
455         return($tail->id());
456     }
457     return undef;
458 }
459
460 sub trailing_tag_parent
461 {
462     my($self)=@_;
463     my $tail=$self->tail();
464     if($self->is("tag", $tail))
465     {
466         return($tail->{parents_id});
467     }
468     return undef;
469 }
470
471 sub tail
472 {
473     my($self)=@_;
474     return($self->{elements}->[$#{$self->{elements}}]);
475 }
476
477 sub at
478 {
479     my($self, $type)=@_;
480     return($self->is($type, $self->tail()));
481 }
482
483 sub is
484 {
485     my($self, $type, $thing)=@_;
486     return 0 unless($thing);
487     return 0 unless($thing->type());
488     return 1 if($type eq $thing->type());
489     return 0;
490 }
491
492 # the one before last
493 sub tail_parent
494 {
495     my($self)=@_;
496     return($self->{elements}->[($#{$self->{elements}}) - 1]);
497 }
498
499 ######################################################################
500
501 sub tags
502 {
503     my($self)=@_;
504     if(!$self->{tagtree}) # / or /NOT
505     {
506         my $sql="SELECT DISTINCT name FROM tags WHERE parents_id='';";
507         return($self->{db}->cmd_firstcol($sql));
508     }
509     my $hasvals=$self->expecting_values();
510     my $parent=$self->trailing_tag_parent();
511 #    print "THASVALS: $hasvals\n";
512 #    print "TPARENT: ", (defined($parent)? $parent : "NO"), "\n";
513     my @ids=();
514     my $sql=("SELECT tags.name FROM (\n" .
515              $self->tags_subselect() .
516              ") AS subselect\n" .
517              "INNER JOIN files_x_tags ON subselect.files_id=files_x_tags.files_id\n" .
518              "INNER JOIN tags ON files_x_tags.tags_id=tags.id\n");
519     my @allused=$self->used_tags();
520     my @used=grep { ref($_) ne "ARRAY"; } @allused;
521     my @used_with_vals=grep { ref($_) eq "ARRAY"; } @allused;
522 #    print "tags(): USED: ", join(", ", @used), "\n";
523 #    print "tags(): USED_WITH_VALS: ", join(", ", map { "[".$_->[0]. ", ".$_->[1]."]";} @used_with_vals), "\n";
524     my @orclauses=();
525     my @andclauses=();
526     my $id=$self->trailing_tag_id();
527     if($hasvals)
528     {
529 #       print "HAS_VALUES\n";
530         my @values=map { "'".$_->[1]."'"; } grep { $_->[0] == $id; } @used_with_vals;
531         my $clause="(tags.parents_id='$id'";
532         if(@values)
533         {
534             $clause .= " AND tags.id NOT IN (" . join(', ', @values) . ")";
535         }
536         $clause .= ")";
537         push(@andclauses, $clause);
538     }
539     else
540     {
541 #       print "HASNT VALUES\n";;
542         if(@used)
543         {
544             push(@andclauses, "(NOT (tags.parents_id='' AND tags.id IN (" . join(', ', @used) . ")))");
545         }
546         for my $pair (@used_with_vals)
547         {
548             push(@andclauses, "(NOT (tags.parents_id='" . $pair->[0] . "' AND tags.id='" . $pair->[1] . "'))");
549         }
550     }
551
552     my $parentclause= "(tags.parents_id='";
553     if($hasvals)
554     {
555         $parentclause .= $id;
556     }
557     elsif($parent)
558     {
559         $parentclause .= $parent;
560     }
561     $parentclause .= "')";
562     push(@andclauses, $parentclause);
563
564     if(@orclauses)
565     {
566         push(@andclauses, '( ' . join(' OR ', @orclauses) . ' )');
567     }
568     if(@andclauses)
569     {
570         $sql .= "WHERE " . join(' AND ', @andclauses) . "\n";
571     }
572     $sql .= "GROUP BY tags.name;";
573     print "SQL(TAGS): $sql\n" if($self->{verbose});
574     my @tagnames=$self->{db}->cmd_firstcol($sql);
575     print("SUBNAMES: ", join(', ', @tagnames), "\n") if($self->{verbose});
576     return(@tagnames);
577 }
578
579 sub artists
580 {
581     my($self)=@_;
582     if(!@{$self->{elements}}) # /ALL
583     {
584         my $sql="SELECT DISTINCT name FROM artists WHERE name!='';";
585         return($self->{db}->cmd_firstcol($sql));
586     }
587     my @ids=();
588     my $sql=$self->sql_start("artists.name");
589     $sql .= ("INNER JOIN artists ON files.artists_id=artists.id\n" .
590              "WHERE artists.name != ''\n" .
591              "GROUP BY artists.name;");
592     print "SQL(ARTISTS): $sql\n" if($self->{verbose});
593     my @tagnames=$self->{db}->cmd_firstcol($sql);
594     print("ARTISTS: ", join(', ', @tagnames), "\n") if($self->{verbose});
595     return(@tagnames);
596 }
597
598 sub albums
599 {
600     my($self)=@_;
601     my @ids=();
602     my $tail=$self->tail();
603     if($self->is("artist", $tail))
604     {
605         return $self->artist_albums($tail->id());
606     }
607     my $sql=$self->sql_start("albums.name");
608     $sql .= ("INNER JOIN albums ON files.albums_id=albums.id\n" .
609              "WHERE albums.name != ''\n" .
610              "GROUP BY albums.name;");
611     print "SQL(ALBUMS): \n$sql\n" if($self->{verbose});
612     my @names=$self->{db}->cmd_firstcol($sql);
613     print("ALBUMS: ", join(', ', @names), "\n") if($self->{verbose});
614     return(@names);
615 }
616
617 sub artist_albums
618 {
619     my($self, $artist_id)=@_;
620     my $sql=$self->sql_start("albums.name");
621     $sql .= ("INNER JOIN albums ON albums.id=files.albums_id\n" .
622              "INNER JOIN artists ON artists.id=files.artists_id\n" .
623              "WHERE artists.id=? and albums.name <> ''\n" .
624              "GROUP BY albums.name\n");
625     print "ARTIST_ALBUMS SQL: $sql\n" if($self->{verbose});
626     my @albums=$self->{db}->cmd_firstcol($sql, $artist_id);
627     print("ALBUMS: ", join(', ', @albums), "\n") if($self->{verbose});
628     return(@albums);
629 }
630
631 sub artist_tracks
632 {
633     my($self, $artist_id)=@_;
634     my $sql=$self->sql_start("files.name");
635     $sql .= ("INNER JOIN artists ON artists.id=files.artists_id\n" .
636              "INNER JOIN albums  ON albums.id=files.albums_id\n" .
637              "WHERE artists.id=? AND albums.name=''\n" .
638              "GROUP BY files.name\n");
639     print "ARTIST_TRACKS SQL: $sql\n" if($self->{verbose});
640     my @names=$self->{db}->cmd_firstcol($sql, $artist_id);
641     print("ARTISTTRACKS: ", join(', ', @names), "\n") if($self->{verbose});
642     return(@names);
643 }
644
645 sub album_tracks
646 {
647     my($self, $artist_id, $album_id)=@_;
648     my $sql=("SELECT files.name FROM files\n" .
649              "INNER JOIN albums  ON albums.id=files.albums_id\n" .
650              "INNER JOIN artists ON artists.id=files.artists_id\n" .
651              "WHERE artists.id=? AND albums.id=?\n" .
652              "GROUP BY files.name\n");
653     print "ALBUM_TRACKS SQL($artist_id, $album_id): $sql\n" if($self->{verbose});
654     my @names=$self->{db}->cmd_firstcol($sql, $artist_id, $album_id);
655     print("TRACKS: ", join(', ', @names), "\n") if($self->{verbose});
656     return(@names);
657 }
658
659 sub tracks
660 {
661     my($self)=@_;
662     my $tail=$self->tail();
663     if($self->is("artist", $tail))
664     {
665         return $self->artist_tracks($tail->id());
666     }
667     elsif($self->is("album", $tail))
668     {
669         my $artist_id=0;
670         my $artist=$self->tail_parent();
671         if($self->is("artist", $artist))
672         {
673             # should always happen
674             $artist_id=$artist->id();
675         }
676         return $self->album_tracks($artist_id, $tail->id());
677     }
678     my $sql=$self->sql_start("files.name");
679     $sql .= "INNER JOIN artists ON files.artists_id=artists.id\n";
680     if($self->{components}->[$#{$self->{components}}] eq $PATH_NOARTIST)
681     {
682         $sql .= "WHERE artists.name =''\n";
683     }
684     $sql .= "GROUP BY files.name;";
685     print "TRACKS SQL($self->{path}): $sql\n" if($self->{verbose});
686     my @names=$self->{db}->cmd_firstcol($sql);
687     print("TRACKS: ", join(', ', @names), "\n") if($self->{verbose});
688     return(@names);
689 }
690
691 sub filename
692 {
693     my($self, $mountpoint)=@_;
694     my $tail=$self->tail();
695     if($self->is("file", $tail))
696     {
697         my $id=$tail->id();
698         my $sql=("SELECT paths.name, files.name FROM files\n" .
699                  "INNER JOIN paths ON files.paths_id=paths.id\n" .
700                  "WHERE files.id=?\n" .
701                  "GROUP BY paths.name, files.name");
702         print "FILENAME SQL: $sql\n" if($self->{verbose});
703         my ($path, $name)=$self->{db}->cmd_onerow($sql, $id);
704         my $id3fs_path=join('/', map { $_->{name}; }  @{$self->{elements}});
705         return($self->{db}->relativise($path, $name, $mountpoint));
706     }
707     # should never happen
708     return "ERROR";
709 }
710
711 sub tags_subselect
712 {
713     my($self)=@_;
714     my $hasvals=$self->expecting_values();
715     # we need to specially handle a bare /NOT/tag with no other clauses,
716     # using a simple WHERE id !='tagid' instead of a LEFT JOIN
717     if($self->{bare_not})
718     {
719         return $self->bare_not_subselect();
720     }
721     if($self->{in_all})
722     {
723         return "\tSELECT id FROM files AS files_id\n";
724     }
725     my $tree=$self->{tagtree};
726     print "UNDEF!!\n" unless($self->{tagtree});
727     use Data::Dumper;
728     print Dumper $tree;
729     my $parent=$self->trailing_tag_parent();
730
731 #    print "ELEMENTS: ", join('/', map { $_->{name}; } @{$self->{elements}}), "\n";
732 #    print "TREE: ", $tree->print(), "\n";
733     my $tag=undef;
734     if($hasvals)
735     {
736         $tag=$self->trailing_tag_id();
737 #       print "Trailing id: $tag\n";
738     }
739     my ($sqlclause, @joins)=(undef, ());
740     ($sqlclause, @joins) = $tree->to_sql($hasvals) if($tree);
741 #    print "SQL(" . scalar(@joins) .": $sqlclause\n";
742     my $sql="\tSELECT fxt1.files_id FROM tags t1";
743     my @crosses=();
744     my @inners=();
745 #    $joinsneeded++ if($tag);
746     for(my $i=0; $i <= $#joins; $i++)
747     {
748         my $cnt=$i+1;
749         my $join=$joins[$i];
750         my $inner=("\t$join JOIN files_x_tags fxt$cnt ON " .
751                    "t${cnt}.id=fxt${cnt}.tags_id");
752         if($i > 0)
753         {
754             push(@crosses, "CROSS JOIN tags t$cnt");
755             $inner .= " AND fxt1.files_id=fxt${cnt}.files_id";
756         }
757         push(@inners, $inner);
758     }
759     $sql .= ("\n\t" . join(" ", @crosses)) if(@crosses);
760     $sql .= ("\n" . join("\n", @inners)) if(@inners);
761     $sql .= "\n\tWHERE $sqlclause" if($sqlclause);
762 #    if($tag)
763 #    {
764 #       $sql .= " AND t${joinsneeded}.parents_id='$tag'";
765 #    }
766     $sql .= "\n\tGROUP BY fxt1.files_id\n";
767     return $sql;
768 }
769
770 sub bare_not_subselect
771 {
772     my($self)=@_;
773     my @tags=grep { $self->is("tag", $_); } @{$self->{elements}};
774     my $sql=("\tSELECT f1.id AS files_id FROM files f1 WHERE f1.id NOT IN (\n" .
775              "\t\tSELECT fxt1.files_id FROM tags t1\n" .
776              "\t\tINNER JOIN files_x_tags fxt1 ON t1.id=fxt1.tags_id\n" .
777              "\t\tWHERE ");
778     if(scalar(@tags) > 1)
779     {
780         $sql .= ("(t1.parents_id='" . $tags[0]->id() . "' AND t1.id='" .
781                  $tags[1]->id() . "')");
782     }
783     else
784     {
785         $sql .= ("(t1.parents_id='' AND t1.id='" . $tags[0]->id() . "')");
786     }
787     $sql .= "\n\t\tGROUP BY fxt1.files_id\n\t)\n";
788     return($sql);
789 }
790
791 sub sql_start
792 {
793     my($self, $tables)=@_;
794     my $sql="SELECT $tables FROM ";
795     if($self->{in_all})
796     {
797         $sql .= "files\n";
798     }
799     else
800     {
801         $sql .= ("(\n" .
802                  $self->tags_subselect() .
803                  ") AS subselect\n" .
804                  "INNER JOIN files ON subselect.files_id=files.id\n");
805     }
806     return $sql;
807 }
808
809
810 sub constraints_tag_list
811 {
812     my($self, @constraints)=@_;
813     my $lasttag=undef;
814     my @tags=();
815     my @tags_vals=();
816     for my $constraint (@constraints)
817     {
818 #       print ref($constraint), ": ", $constraint->{name}, "\n";
819         if($self->is("tag", $constraint))
820         {
821             if(defined($lasttag))
822             {
823 #               print "TAGVAL\n";
824                 push(@tags_vals, [$lasttag, $constraint->id()]) if defined($constraint->id());
825                 $lasttag=undef;
826             }
827             elsif($self->tag_has_values($constraint->id()))
828             {
829 #               print "HASVALUES\n";
830                 $lasttag=$constraint->id() if defined($constraint->id());
831             }
832             else
833             {
834 #               print "NOVALUES\n";
835                 push(@tags, $constraint->id()) if(defined($constraint->id()));
836             }
837         }
838     }
839     @tags=map{ "\"$_\""; } @tags;
840     @tags_vals=map( { [ map({ "\"$_\""; } @$_ ) ] } @tags_vals);
841     $lasttag="\"$lasttag\"" if defined($lasttag);
842     return(\@tags, \@tags_vals, $lasttag);
843 }
844
845 # we just filter $ALLTRACKS, $NOARTIST and $NOALBUM
846 # filtering tags properly requires up to four levels of recursion
847 # (tag/tagval/AND/NOT) and is too slow
848 sub filter
849 {
850     my($self, @dirs)=@_;
851     my $base=$self->{path};
852     my @outdirs=();
853     for my $dir (@dirs)
854     {
855         print "\nFILTER (",$self->state(), "): $base / $dir\n";
856         if($self->empty("$base/$dir"))
857         {
858             print "empty: $base / $dir\n";
859         }
860         else
861         {
862             print "non-empty, accepting: $base / $dir\n";
863             push(@outdirs, $dir);
864         }
865     }
866     return(@outdirs);
867 }
868
869 sub empty
870 {
871     my($self, $dir)=@_;
872     my $path=ID3FS::Path->new($self->{db}, $dir, $self->{verbose},
873                               ($self->{maxtagdepth} - $self->{curtagdepth}));
874     return 1 unless($path->isvalid());
875     my($subdirs,$subfiles)=$path->dirents();
876     return 0 if(@$subfiles || @$subdirs);
877     return 1;
878 }
879
880 1;