<?_code
{
    my $lang = $FORM{'lang'};
    my $l = LJ::Lang::get_lang($lang);
    return "<b>Invalid language</b>" unless $l;

    my $dbr = LJ::get_db_reader();
    my $sth;
 
    my $sql;

    if ($FORM{'search'} eq 'sev') 
    {
        my $what = ">= 1";
        if ($FORM{'stale'} =~ /^(\d+)(\+?)$/) {
            $what = ($2 ? ">=" : "=") . $1;
        }
        $sql = "SELECT i.dmid, i.itid, i.itcode FROM ml_items i, ml_latest l WHERE l.lnid=$l->{'lnid'} AND l.staleness $what AND l.dmid=i.dmid AND l.itid=i.itid ORDER BY i.dmid, i.itcode";
    }
    
    if ($FORM{'search'} eq 'txt') 
    {
        my $remote = LJ::get_remote();
        return "This search type is restricted to $l->{'lnname'} translators." unless
            (LJ::check_priv($remote, "translate", "*") ||
             LJ::check_priv($remote, "translate", $l->{'lncode'}) ||
             LJ::check_priv($remote, "faqedit", "*")); # FAQ admins can search too

        my $qtext = $dbr->quote($FORM{'searchtext'});
        my $dmid = $FORM{'searchdomain'}+0;
        my $dmidwhere = $dmid ? "AND i.dmid=$dmid" : "";
        if ($FORM{'searchwhat'} eq "code") {
            $sql = qq{
                SELECT i.dmid, i.itid, i.itcode FROM ml_items i, ml_latest l
                WHERE l.lnid=$l->{'lnid'} AND l.dmid=i.dmid AND i.itid=l.itid 
                $dmidwhere AND LOCATE($qtext, i.itcode)
            };
        } else {
            my $lnid = $l->{'lnid'};
            if ($FORM{'searchwhat'} eq "parent") { $lnid = $l->{'parentlnid'}; }
            $sql = qq{
                SELECT i.dmid, i.itid, i.itcode FROM ml_items i, ml_latest l, ml_text t
                WHERE l.lnid=$lnid AND l.dmid=i.dmid AND i.itid=l.itid 
                $dmidwhere AND t.dmid=l.dmid AND t.txtid=l.txtid AND LOCATE($qtext, t.text)
                ORDER BY i.itcode
            };
        }        
    }

    return "Bogus or unimplemented query type." unless $sql;

    my $ret;
    $sth = $dbr->prepare($sql);
    $sth->execute;
    my $page = 0;
    my @page = ();
    my $addlink = sub {
        return unless @page;
        $page++;
        my $link = "editpage.bml?lang=$lang&amp;items=" . LJ::eurl(join(",",map{"$_->[0]:$_->[1]"}@page));
        $ret .= "<b><a target='main' href='$link'>Page $page</a></b><br /><span style='font-size:8pt'>\n";
        $ret .= "$page[0]->[2]<br />\n";
        $ret .= "$page[-1]->[2]<br /></span>\n";
        @page = ();
    };
    while (my ($dmid, $itid, $itcode) = $sth->fetchrow_array) {
        push @page, [ $dmid, $itid, $itcode ];
        $addlink->() if @page >= 10;
    }
    $addlink->();
 
    if ($page == 0) { $ret .= "<i>(No matches)</i>"; }
    
    return $ret;
    
}
_code?>
