aa2e62ea21081af3c9e39c838a351743baefc068
[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     }
358 }
359
360 sub state
361 {
362     my($self, $newstate)=@_;
363     if(defined($newstate))
364     {
365         $self->{state}=$newstate;
366         $self->{curtagdepth}++ if($newstate == $STATE_TAG);
367     }
368     return $self->{state};
369 }
370
371 sub elements_to_tree
372 {
373     my($self, $elements)=@_;
374     return undef unless(@$elements);
375     my ($left, $right, $op)=(undef, undef, undef);
376     my $thing=pop @$elements;
377     if($self->is("boolean", $thing))
378     {
379         $right=$self->elements_to_tree($elements);
380         if($thing->{name} ne "NOT")
381         {
382             $left=$self->elements_to_tree($elements);
383         }
384         $thing->left($left);
385         $thing->right($right);
386     }
387     return $thing;
388 }
389
390 # Dijkstra's shunting-yard algorithm
391 sub sort_elements
392 {
393     my ($self, @input)=@_;
394     my @opstack=();
395     my @output=();
396 #    print "INPUT: ", join(', ', map { $_->{name}; } @input), "\n";
397     while(my $thing = shift @input)
398     {
399         if($self->is("tag", $thing))
400         {
401             # Handle tag values by dropping parent
402             if(@input && $self->is("tag", $input[0]))
403             {
404                 $thing=shift @input;
405             }
406             push(@output, $thing);
407         }
408         elsif($self->is("boolean", $thing))
409         {
410             # bool
411             while(@opstack &&
412                   ($priorities{$thing->{name}} <= $priorities{$opstack[$#opstack]->{name}}))
413             {
414                 push(@output, pop(@opstack));
415             }
416             push(@opstack, $thing);
417         }
418     }
419     while(@opstack)
420     {
421         push(@output, pop(@opstack));
422     }
423 #    print "STACK: ", join(', ', map { $_->{name}; } @output), "\n";
424     return @output;
425 }
426
427 sub used_tags
428 {
429     my($self)=@_;
430     return() unless(defined($self->{tagtree}));
431     return($self->{tagtree}->used_tags());
432 }
433
434 sub expecting_values
435 {
436     my($self)=@_;
437     my $tail=$self->tail();
438     if($self->is("tag", $tail))
439     {
440         return($self->{db}->tag_has_values($tail->id()));
441     }
442 }
443
444 sub trailing_tag_id
445 {
446     my($self)=@_;
447     my $tail=$self->tail();
448     if($self->is("tag", $tail))
449     {
450         return($tail->id());
451     }
452     return undef;
453 }
454
455 sub trailing_tag_parent
456 {
457     my($self)=@_;
458     my $tail=$self->tail();
459     if($self->is("tag", $tail))
460     {
461         return($tail->{parents_id});
462     }
463     return undef;
464 }
465
466 sub tail
467 {
468     my($self)=@_;
469     return($self->{elements}->[$#{$self->{elements}}]);
470 }
471
472 sub at
473 {
474     my($self, $type)=@_;
475     return($self->is($type, $self->tail()));
476 }
477
478 sub is
479 {
480     my($self, $type, $thing)=@_;
481     return 0 unless($thing);
482     return 0 unless($thing->type());
483     return 1 if($type eq $thing->type());
484     return 0;
485 }
486
487 # the one before last
488 sub tail_parent
489 {
490     my($self)=@_;
491     return($self->{elements}->[($#{$self->{elements}}) - 1]);
492 }
493
494 ######################################################################
495
496 sub tags
497 {
498     my($self)=@_;
499     if(!$self->{tagtree}) # / or /NOT
500     {
501         my $sql="SELECT DISTINCT name FROM tags WHERE parents_id='';";
502         return($self->{db}->cmd_firstcol($sql));
503     }
504     my $hasvals=$self->expecting_values();
505     my $parent=$self->trailing_tag_parent();
506 #    print "THASVALS: $hasvals\n";
507 #    print "TPARENT: ", (defined($parent)? $parent : "NO"), "\n";
508     my @ids=();
509     my $sql=("SELECT tags.name FROM (\n" .
510              $self->tags_subselect() .
511              ") AS subselect\n" .
512              "INNER JOIN files_x_tags ON subselect.files_id=files_x_tags.files_id\n" .
513              "INNER JOIN tags ON files_x_tags.tags_id=tags.id\n");
514     my @allused=$self->used_tags();
515     my @used=grep { ref($_) ne "ARRAY"; } @allused;
516     my @used_with_vals=grep { ref($_) eq "ARRAY"; } @allused;
517 #    print "tags(): USED: ", join(", ", @used), "\n";
518 #    print "tags(): USED_WITH_VALS: ", join(", ", map { "[".$_->[0]. ", ".$_->[1]."]";} @used_with_vals), "\n";
519     my @orclauses=();
520     my @andclauses=();
521     my $id=$self->trailing_tag_id();
522     if($hasvals)
523     {
524 #       print "HAS_VALUES\n";
525         my @values=map { "'".$_->[1]."'"; } grep { $_->[0] == $id; } @used_with_vals;
526         my $clause="(tags.parents_id='$id'";
527         if(@values)
528         {
529             $clause .= " AND tags.id NOT IN (" . join(', ', @values) . ")";
530         }
531         $clause .= ")";
532         push(@andclauses, $clause);
533     }
534     else
535     {
536 #       print "HASNT VALUES\n";;
537         if(@used)
538         {
539             push(@andclauses, "(NOT (tags.parents_id='' AND tags.id IN (" . join(', ', @used) . ")))");
540         }
541         for my $pair (@used_with_vals)
542         {
543             push(@andclauses, "(NOT (tags.parents_id='" . $pair->[0] . "' AND tags.id='" . $pair->[1] . "'))");
544         }
545     }
546
547     my $parentclause= "(tags.parents_id='";
548     if($hasvals)
549     {
550         $parentclause .= $id;
551     }
552     elsif($parent)
553     {
554         $parentclause .= $parent;
555     }
556     $parentclause .= "')";
557     push(@andclauses, $parentclause);
558
559     if(@orclauses)
560     {
561         push(@andclauses, '( ' . join(' OR ', @orclauses) . ' )');
562     }
563     if(@andclauses)
564     {
565         $sql .= "WHERE " . join(' AND ', @andclauses) . "\n";
566     }
567     $sql .= "GROUP BY tags.name;";
568     print "SQL(TAGS): $sql\n" if($self->{verbose});
569     my @tagnames=$self->{db}->cmd_firstcol($sql);
570     print("SUBNAMES: ", join(', ', @tagnames), "\n") if($self->{verbose});
571     return(@tagnames);
572 }
573
574 sub artists
575 {
576     my($self)=@_;
577     if(!@{$self->{elements}}) # /ALL
578     {
579         my $sql="SELECT DISTINCT name FROM artists WHERE name!='';";
580         return($self->{db}->cmd_firstcol($sql));
581     }
582     my @ids=();
583     my $sql=$self->sql_start("artists.name");
584     $sql .= ("INNER JOIN artists ON files.artists_id=artists.id\n" .
585              "WHERE artists.name != ''\n" .
586              "GROUP BY artists.name;");
587     print "SQL(ARTISTS): $sql\n" if($self->{verbose});
588     my @tagnames=$self->{db}->cmd_firstcol($sql);
589     print("ARTISTS: ", join(', ', @tagnames), "\n") if($self->{verbose});
590     return(@tagnames);
591 }
592
593 sub albums
594 {
595     my($self)=@_;
596     my @ids=();
597     my $tail=$self->tail();
598     if($self->is("artist", $tail))
599     {
600         return $self->artist_albums($tail->id());
601     }
602     my $sql=$self->sql_start("albums.name");
603     $sql .= ("INNER JOIN albums ON files.albums_id=albums.id\n" .
604              "WHERE albums.name != ''\n" .
605              "GROUP BY albums.name;");
606     print "SQL(ALBUMS): \n$sql\n" if($self->{verbose});
607     my @names=$self->{db}->cmd_firstcol($sql);
608     print("ALBUMS: ", join(', ', @names), "\n") if($self->{verbose});
609     return(@names);
610 }
611
612 sub artist_albums
613 {
614     my($self, $artist_id)=@_;
615     my $sql=$self->sql_start("albums.name");
616     $sql .= ("INNER JOIN albums ON albums.id=files.albums_id\n" .
617              "INNER JOIN artists ON artists.id=files.artists_id\n" .
618              "WHERE artists.id=? and albums.name <> ''\n" .
619              "GROUP BY albums.name\n");
620     print "ARTIST_ALBUMS SQL: $sql\n" if($self->{verbose});
621     my @albums=$self->{db}->cmd_firstcol($sql, $artist_id);
622     print("ALBUMS: ", join(', ', @albums), "\n") if($self->{verbose});
623     return(@albums);
624 }
625
626 sub artist_tracks
627 {
628     my($self, $artist_id)=@_;
629     my $sql=$self->sql_start("files.name");
630     $sql .= ("INNER JOIN artists ON artists.id=files.artists_id\n" .
631              "INNER JOIN albums  ON albums.id=files.albums_id\n" .
632              "WHERE artists.id=? AND albums.name=''\n" .
633              "GROUP BY files.name\n");
634     print "ARTIST_TRACKS SQL: $sql\n" if($self->{verbose});
635     my @names=$self->{db}->cmd_firstcol($sql, $artist_id);
636     print("ARTISTTRACKS: ", join(', ', @names), "\n") if($self->{verbose});
637     return(@names);
638 }
639
640 sub album_tracks
641 {
642     my($self, $artist_id, $album_id)=@_;
643     my $sql=("SELECT files.name FROM files\n" .
644              "INNER JOIN albums  ON albums.id=files.albums_id\n" .
645              "INNER JOIN artists ON artists.id=files.artists_id\n" .
646              "WHERE artists.id=? AND albums.id=?\n" .
647              "GROUP BY files.name\n");
648     print "ALBUM_TRACKS SQL($artist_id, $album_id): $sql\n" if($self->{verbose});
649     my @names=$self->{db}->cmd_firstcol($sql, $artist_id, $album_id);
650     print("TRACKS: ", join(', ', @names), "\n") if($self->{verbose});
651     return(@names);
652 }
653
654 sub tracks
655 {
656     my($self)=@_;
657     my $tail=$self->tail();
658     if($self->is("artist", $tail))
659     {
660         return $self->artist_tracks($tail->id());
661     }
662     elsif($self->is("album", $tail))
663     {
664         my $artist_id=0;
665         my $artist=$self->tail_parent();
666         if($self->is("artist", $artist))
667         {
668             # should always happen
669             $artist_id=$artist->id();
670         }
671         return $self->album_tracks($artist_id, $tail->id());
672     }
673     my $sql=$self->sql_start("files.name");
674     $sql .= "INNER JOIN artists ON files.artists_id=artists.id\n";
675     if($self->{components}->[$#{$self->{components}}] eq $PATH_NOARTIST)
676     {
677         $sql .= "WHERE artists.name =''\n";
678     }
679     $sql .= "GROUP BY files.name;";
680     print "TRACKS SQL($self->{path}): $sql\n" if($self->{verbose});
681     my @names=$self->{db}->cmd_firstcol($sql);
682     print("TRACKS: ", join(', ', @names), "\n") if($self->{verbose});
683     return(@names);
684 }
685
686 sub filename
687 {
688     my($self, $mountpoint)=@_;
689     my $tail=$self->tail();
690     if($self->is("file", $tail))
691     {
692         my $id=$tail->id();
693         my $sql=("SELECT paths.name, files.name FROM files\n" .
694                  "INNER JOIN paths ON files.paths_id=paths.id\n" .
695                  "WHERE files.id=?\n" .
696                  "GROUP BY paths.name, files.name");
697         print "FILENAME SQL: $sql\n" if($self->{verbose});
698         my ($path, $name)=$self->{db}->cmd_onerow($sql, $id);
699         my $id3fs_path=join('/', map { $_->{name}; }  @{$self->{elements}});
700         return($self->{db}->relativise($path, $name, $mountpoint));
701     }
702     # should never happen
703     return "ERROR";
704 }
705
706 sub tags_subselect
707 {
708     my($self)=@_;
709     my $hasvals=$self->expecting_values();
710     # we need to specially handle a bare /NOT/tag with no other clauses,
711     # using a simple WHERE id !='tagid' instead of a LEFT JOIN
712     if($self->{bare_not})
713     {
714         return $self->bare_not_subselect();
715     }
716     if($self->{in_all})
717     {
718         return "\tSELECT id FROM files AS files_id\n";
719     }
720     my $tree=$self->{tagtree};
721     print "UNDEF!!\n" unless($self->{tagtree});
722     my $parent=$self->trailing_tag_parent();
723
724 #    print "ELEMENTS: ", join('/', map { $_->{name}; } @{$self->{elements}}), "\n";
725 #    print "TREE: ", $tree->print(), "\n";
726     my $tag=undef;
727     if($hasvals)
728     {
729         $tag=$self->trailing_tag_id();
730 #       print "Trailing id: $tag\n";
731     }
732     my ($sqlclause, @joins)=(undef, ());
733     ($sqlclause, @joins) = $tree->to_sql($hasvals) if($tree);
734 #    print "SQL(" . scalar(@joins) .": $sqlclause\n";
735     my $sql="\tSELECT fxt1.files_id FROM tags t1";
736     my @crosses=();
737     my @inners=();
738 #    $joinsneeded++ if($tag);
739     for(my $i=0; $i <= $#joins; $i++)
740     {
741         my $cnt=$i+1;
742         my $join=$joins[$i];
743         my $inner=("\t$join JOIN files_x_tags fxt$cnt ON " .
744                    "t${cnt}.id=fxt${cnt}.tags_id");
745         if($i > 0)
746         {
747             push(@crosses, "CROSS JOIN tags t$cnt");
748             $inner .= " AND fxt1.files_id=fxt${cnt}.files_id";
749         }
750         push(@inners, $inner);
751     }
752     $sql .= ("\n\t" . join(" ", @crosses)) if(@crosses);
753     $sql .= ("\n" . join("\n", @inners)) if(@inners);
754     $sql .= "\n\tWHERE $sqlclause" if($sqlclause);
755 #    if($tag)
756 #    {
757 #       $sql .= " AND t${joinsneeded}.parents_id='$tag'";
758 #    }
759     $sql .= "\n\tGROUP BY fxt1.files_id\n";
760     return $sql;
761 }
762
763 sub bare_not_subselect
764 {
765     my($self)=@_;
766     my @tags=grep { $self->is("tag", $_); } @{$self->{elements}};
767     my $sql=("\tSELECT f1.id AS files_id FROM files f1 WHERE f1.id NOT IN (\n" .
768              "\t\tSELECT fxt1.files_id FROM tags t1\n" .
769              "\t\tINNER JOIN files_x_tags fxt1 ON t1.id=fxt1.tags_id\n" .
770              "\t\tWHERE ");
771     if(scalar(@tags) > 1)
772     {
773         $sql .= ("(t1.parents_id='" . $tags[0]->id() . "' AND t1.id='" .
774                  $tags[1]->id() . "')");
775     }
776     else
777     {
778         $sql .= ("(t1.parents_id='' AND t1.id='" . $tags[0]->id() . "')");
779     }
780     $sql .= "\n\t\tGROUP BY fxt1.files_id\n\t)\n";
781     return($sql);
782 }
783
784 sub sql_start
785 {
786     my($self, $tables)=@_;
787     my $sql="SELECT $tables FROM ";
788     if($self->{in_all})
789     {
790         $sql .= "files\n";
791     }
792     else
793     {
794         $sql .= ("(\n" .
795                  $self->tags_subselect() .
796                  ") AS subselect\n" .
797                  "INNER JOIN files ON subselect.files_id=files.id\n");
798     }
799     return $sql;
800 }
801
802
803 sub constraints_tag_list
804 {
805     my($self, @constraints)=@_;
806     my $lasttag=undef;
807     my @tags=();
808     my @tags_vals=();
809     for my $constraint (@constraints)
810     {
811 #       print ref($constraint), ": ", $constraint->{name}, "\n";
812         if($self->is("tag", $constraint))
813         {
814             if(defined($lasttag))
815             {
816 #               print "TAGVAL\n";
817                 push(@tags_vals, [$lasttag, $constraint->id()]) if defined($constraint->id());
818                 $lasttag=undef;
819             }
820             elsif($self->tag_has_values($constraint->id()))
821             {
822 #               print "HASVALUES\n";
823                 $lasttag=$constraint->id() if defined($constraint->id());
824             }
825             else
826             {
827 #               print "NOVALUES\n";
828                 push(@tags, $constraint->id()) if(defined($constraint->id()));
829             }
830         }
831     }
832     @tags=map{ "\"$_\""; } @tags;
833     @tags_vals=map( { [ map({ "\"$_\""; } @$_ ) ] } @tags_vals);
834     $lasttag="\"$lasttag\"" if defined($lasttag);
835     return(\@tags, \@tags_vals, $lasttag);
836 }
837
838 # we just filter $ALLTRACKS, $NOARTIST and $NOALBUM
839 # filtering tags properly requires up to four levels of recursion
840 # (tag/tagval/AND/NOT) and is too slow
841 sub filter
842 {
843     my($self, @dirs)=@_;
844     my $base=$self->{path};
845     my @outdirs=();
846     for my $dir (@dirs)
847     {
848 #       print "\nFILTER (",$self->state(), "): $base / $dir\n";
849         if($self->empty("$base/$dir"))
850         {
851 #           print "empty: $base / $dir\n";
852         }
853         else
854         {
855 #           print "non-empty, accepting: $base / $dir\n";
856             push(@outdirs, $dir);
857         }
858     }
859     return(@outdirs);
860 }
861
862 sub empty
863 {
864     my($self, $dir)=@_;
865     my $path=ID3FS::Path->new($self->{db}, $dir, $self->{verbose},
866                               ($self->{maxtagdepth} - $self->{curtagdepth}));
867     return 1 unless($path->isvalid());
868     my($subdirs,$subfiles)=$path->dirents();
869     return 0 if(@$subfiles || @$subdirs);
870     return 1;
871 }
872
873 1;