Search code examples
hookmediawikimediawiki-extensions

How do I return text from the MediaWiki SearchAfterNoDirectMatch hook?


I am trying to write a MediaWiki Search Hook that will list native files in the file system and then, eventually, allow a person to click on one of the files and view its content.

My extensions.json contains this:

        "Hooks": {
            "SearchAfterNoDirectMatch": "MediaWiki\\Extension\\NativeFileList\\Hooks::onSearchAfterNoDirectMatch"
        },

My Hooks::onSearchAfterNoDirectMatch file looks like this:

namespace MediaWiki\Extension\NativeFileList;

class Hooks {
        /**
         * @see https://www.mediawiki.org/wiki/Manual:Hooks/SearchAfterNoDirectMatch
         * @called from https://gerrit.wikimedia.org/g/mediawiki/core/+/master/includes/search/SearchNearMatcher.php
         * @param $searchterm
         * @param $title - array of titles
         * Returns true if it found something, false is otherwise
         */
        public static function onSearchAfterNoDirectMatch( $searchterm, &$title ) {
           $title=Title::newFromText( "test", "bar");
           return false;
    }

}

My problem is that no text is returned. Well, it's worse than that. With the above code, I get an exception (but I don't know how to debug it, because I can't see the exception). If I take the line setting $title out, it returns. If i change the line to $title=undefined(); I get another error. If I set $title="foo"; I get no error, but no foo.

So how do I return a search hit or, even better, a set of search hits?

None of the existing search plug-ins use the modern search Hook api, which is documented in these locations:


Solution

  • SearchAfterNoDirectMatch is used to return the title of a near-match, rather than to supplement the search results. For supplementing search results, use the onSpecialSearchResultsAppend. Here is code adds three lines to the search results:

    class Hooks {
        /**
         * @see https://www.mediawiki.org/wiki/Manual:Hooks/SearchAfterNoDirectMatch
         * @called from https://gerrit.wikimedia.org/g/mediawiki/core/+/master/includes/search/SearchNearMatcher.php
         * @param $searchterm
         * @param $title - array of titles
         */
        public static function onSpecialSearchResultsAppend( $that, $out, $term ) {
            $out->addHTML("<h3>Extra Search Results:</h3>");
                $out->addHTML("<ul>");
                $out->addHTML("<li>Extra Result #1</li>");
                $out->addHTML("<li>Extra Result #2</li>");
                $out->addHTML("<li>Extra Result #3</li>");
                $out->addHTML("</ul>");
            }
        }
    }
    

    That should be enough to get most people going.