St Johnstone progressed to the semi-finals of the Scottish Cup after beating Raith Rovers 3-1 in a pulsating match at Stark's Park.