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