From 88a11c137735523bdb85ede1744bd36da70162b0 Mon Sep 17 00:00:00 2001
From: rxu <rxu@mail.ru>
Date: Sat, 13 Nov 2021 17:24:25 +0700
Subject: [PATCH] [ticket/16908] Fix PHP warning on non-existent post id
 requests

PHPBB3-16908
---
 phpBB/posting.php                 | 11 ++++++-----
 tests/functional/posting_test.php | 22 ++++++++++++++++++++++
 2 files changed, 28 insertions(+), 5 deletions(-)

diff --git a/phpBB/posting.php b/phpBB/posting.php
index bc3e28ca43..736812cfaf 100644
--- a/phpBB/posting.php
+++ b/phpBB/posting.php
@@ -87,24 +87,25 @@ switch ($mode)
 		$post_id = $request->variable('p', 0);
 		if ($post_id)
 		{
-			$topic_forum = array();
+			$topic_forum = [];
 
 			$sql = 'SELECT t.topic_id, t.forum_id
 				FROM ' . TOPICS_TABLE . ' t, ' . POSTS_TABLE . ' p
 				WHERE p.post_id = ' . $post_id . '
 				AND t.topic_id = p.topic_id';
 			$result = $db->sql_query($sql);
-			$topic_forum = $db->sql_fetchrow();
-			$topic_id = (int) $topic_forum['topic_id'];
-			$forum_id = (int) $topic_forum['forum_id'];
+			$topic_forum = $db->sql_fetchrow($result);
 			$db->sql_freeresult($result);
 		}
 
-		if (!$post_id || !$topic_id || !$forum_id)
+		if (!$post_id || !$topic_forum)
 		{
 			$user->setup('posting');
 			trigger_error('NO_POST');
 		}
+
+		$topic_id = (int) $topic_forum['topic_id'];
+		$forum_id = (int) $topic_forum['forum_id'];
 	break;
 }
 
diff --git a/tests/functional/posting_test.php b/tests/functional/posting_test.php
index 30aab0afa1..363b5f4a18 100644
--- a/tests/functional/posting_test.php
+++ b/tests/functional/posting_test.php
@@ -300,4 +300,26 @@ class phpbb_functional_posting_test extends phpbb_functional_test_case
 			$crawler->filter('#preview .content')->html()
 		);
 	}
+
+	public function nonexistent_post_id_data()
+	{
+		$nonexistent_post_id = 999999; // Random value
+		return [
+			['edit', $nonexistent_post_id],
+			['delete', $nonexistent_post_id],
+			['quote', $nonexistent_post_id],
+			['soft_delete', $nonexistent_post_id],
+		];
+	}
+
+	/**
+	 * @dataProvider nonexistent_post_id_data
+	 */
+	public function test_nonexistent_post_id($mode, $nonexistent_post_id)
+	{
+		$this->add_lang('posting');
+		$this->login();
+		$crawler = self::request('GET', "posting.php?mode={$mode}&p={$nonexistent_post_id}&sid={$this->sid}");
+		$this->assertContainsLang('NO_POST', $crawler->text());
+	}
 }