Sumner M. Redstone, the aging media mogul, has settled a long-running legal battle with his former girlfriend Manuela Herzer, capping a dispute that challenged Mr. Redstone’s mental capacity and sowed doubt over the future of his empire. The settlement includes Mr. Redstone’s daughter, Shari E. Redstone, who has taken a leadership role in Viacom and CBS. The Redstones control both companies through their private theater chain, National Amusements. As part of the agreement, Ms. Herzer will pay back $3.25 million for the lavish gifts and monetary rewards Mr. Redstone had given her over the years. Ms. Herzer had been named a beneficiary of Mr. Redstone’s will, and she would have stood to receive $50 million and his $20 million mansion. He will turn 96 in May 2019. In 2015, Mr. Redstone forced Ms. Herzer, who is at least four decades his junior, out of his mansion in Beverly Hills and removed her from his will. As Mr. Redstone’s health deteriorated in recent years, a war had broken out over who would control the businesses. Any doubt over his mental capacity put pressure on the Redstone family. At stake were the fortunes of his family and several former confidants as well as the fate of Viacom and CBS. But a settlement agreement in 2016 left Mr. Redstone and Ms. Redstone in firm control of the empire.