From 4a4e8d3f9208b04533fde9eec678cb7c6e58ecb7 Mon Sep 17 00:00:00 2001 From: Edward Chernenko Date: Fri, 20 Sep 2024 23:29:22 +0300 Subject: [PATCH] Search categories for candidates in the correct order This prevents a situation when two categories (A and B) have the same image, category A is (according to sortkey order) more important, but it gets no recommendation, because this image got assigned to B. After this change, categories are searched in their sortkey order, so category A will always get this filename before category B. --- includes/Hooks.php | 20 ++++++++------------ 1 file changed, 8 insertions(+), 12 deletions(-) diff --git a/includes/Hooks.php b/includes/Hooks.php index bd059df..e6f6483 100644 --- a/includes/Hooks.php +++ b/includes/Hooks.php @@ -133,9 +133,6 @@ public function onImagePageAfterImageLinks( $imagePage, &$html ) { } // Randomly choose up to $wgRelatedImagesMaxImagesPerCategory titles (not equal to $title) from $categoryNames. - $filenamesPerCategory = []; # [ 'Category_name' => [ 'filename', ... ], ... ] - $seenFilenames = []; - $res = $dbr->newSelectQueryBuilder() ->select( [ 'page_title AS filename', @@ -154,6 +151,11 @@ public function onImagePageAfterImageLinks( $imagePage, &$html ) { ->caller( __METHOD__ ) ->fetchResultSet(); + // List of candidates to recommend (in the same order as $categoryNames): + // [ 'Category_name' => [ 'filename', ... ], ... ] + $filenamesPerCategory = array_fill_keys( $categoryNames, [] ); + $seenFilenames = []; + foreach ( $res as $row ) { if ( isset( $seenFilenames[$row->filename] ) ) { // Already recommended in another category. @@ -168,20 +170,15 @@ public function onImagePageAfterImageLinks( $imagePage, &$html ) { continue; } - if ( !isset( $filenamesPerCategory[$row->category] ) ) { - $filenamesPerCategory[$row->category] = []; - } - if ( count( $filenamesPerCategory[$row->category] ) < $wgRelatedImagesMaxImagesPerCategory ) { $filenamesPerCategory[$row->category][] = $row->filename; } } $logger = LoggerFactory::getInstance( 'RelatedImages' ); - $logger->debug( 'RelatedImages: file={file}, categoryOrder={categoryOrder}, filenamesPerCategory: {candidates}', + $logger->debug( 'RelatedImages: file={file}, filenamesPerCategory: {candidates}', [ - 'file' => $title->getFullText(), - 'categoryOrder' => implode( '|', $categoryNames ), + 'file' => $title->getDBKey(), 'candidates' => FormatJson::encode( $filenamesPerCategory ) ] ); @@ -195,8 +192,7 @@ public function onImagePageAfterImageLinks( $imagePage, &$html ) { $thumbsize = $this->getThumbnailSize(); $numCategoriesCount = 0; - foreach ( $categoryNames as $category ) { - $filenames = $filenamesPerCategory[$category] ?? []; + foreach ( $filenamesPerCategory as $category => $filenames ) { if ( !$filenames ) { continue; }